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 trial
Aren't we supposed to avoid updating state directly?
In previous videos we were advised to update state indirectly by making a copy of state and then modifying the copy, and not the original state. But here it was modified directly with
this.state.value. I'm trying to understand when we can change state directly vs. indirectly.
Laura CoronelTreehouse Teacher
Hey Tyler McDonald! Great question. So in video we are setting the value of the input tag to be the value state (
this.state.value) we are actually modifying the stat in the
handleValueChange function by using the setState method.
For your main question: When to change state directly vs. indirectly? Change the code directly when you want to change the whole state. I.e changing the value state to equal the input value (
If you manipulate the state directly React may not notice the state change b/c the object/array's reference is the same. Since they are passed by reference you need to create a new copy of the object or array with the spread operator (
...) so you get a new reference and React will noticed you passed new data as state.
I hope this is helpful! I see you're on slack! Feel free to reach out if you would like to talk about this more!