Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSaud Tauqeer
Courses Plus Student 8,099 Pointson 7:25 timestamp.
is it a bad practice to directly mutate state like for something like this?
this.state.value = ""
//whereas what guil does is
this.setState({ value: "" });
1 Answer
Michael Hulet
47,913 PointsIn React, you should never modify the state
directly, and you should always call setState
instead. This is so that React knows the state
has changed, and React can re-render the DOM how it likes, using whatever optimizations it can make
Saud Tauqeer
Courses Plus Student 8,099 PointsSaud Tauqeer
Courses Plus Student 8,099 PointsThank you
Gari Merrifield
9,598 PointsGari Merrifield
9,598 PointsThat being a general principle in OOP, keep your data encapsulated/private and use set/get methods for writing and reading the values.
Seokhyun Wie
Full Stack JavaScript Techdegree Graduate 21,606 PointsSeokhyun Wie
Full Stack JavaScript Techdegree Graduate 21,606 PointsMichael Hulet I also tried to write the code myself first, and I ended up writing as him.
this.state.value = ""
However, it didn't have any problem running the app, so my question is that the core reason using
setState
to modify any state is only because to let React know about the change, not because any possibility of errors? Just want to know the conceptual reasons. Thanks.