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!

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 trial

JavaScript React Components (2018) Managing State and Data Flow Adding Items to State

on 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
Michael Hulet
47,909 Points

In 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

Thank you

Gari Merrifield
Gari Merrifield
9,597 Points

That being a general principle in OOP, keep your data encapsulated/private and use set/get methods for writing and reading the values.

Seokhyun Wie
.a{fill-rule:evenodd;}techdegree seal-36
Seokhyun Wie
Full Stack JavaScript Techdegree Graduate 21,606 Points

Michael 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.