A React Rule: Never Directly Modify State

David Joseph Katz
A free video tutorial from David Joseph Katz
Software Engineer
4.4 instructor rating • 19 courses • 234,771 students

Lecture description

An explanation of one of the golden rules of react: never directly modify the state object in the component.

Learn more from the full course

React JS Web Development - The Essentials Bootcamp

Bootcamp on the React.js essentials. Gain a strong foundation of the core concepts, and build exciting and useful apps!

10:33:13 of on-demand video • Updated August 2019

  • Learn React the right and learn best practices.
  • Dive into the React engine, and learn how it works under the hood.
  • See how React fits in the big picture of web development.
  • Learn how to build applications from scratch.
  • Cover the crucial concepts of bundling and transpiling, and create frontend application build systems.
English It's time to lay down the law. Make sure that you remember this react rule never directly modify state. More completely, Never directly modify the component state if your intention is for changes to occur in the render method based on updated state values. Let's look at examples in determining whether or not they're following this rule. First up we have this line of code in this case. This.state.displayBio is getting set to a new value not as far as javascript code goes. This syntax seems fine in other non react applications. This line of code could potentially be relevant. But in react this is a bad practice. It's directly modifying the state. The way to properly do this is to call setState. Give setState an object and then have the relevant key that you want to update, then the value that it should update to, when you call setState itself. All right, before we get into why the setState approach is required. Take a look at another example. Take this line of code. It's attempting to update a text variable in the state object by adding three periods to the text key. Now is this a bad example or recommending an example of updating the state? And it's definitely bad. This is another example of directly modifying the state. Again the code itself isn't bad javascript. This is a valid way to do string concatenation and add three periods to an existing string. But it's just not the way in react that you want to reflect changes in the render method. Instead the proper approach again is a call to setState and the text key and have the value be a whole new string with this.state.text and adding the three periods to it. Still even with these examples the main question still hasn't been answered. Why is it a rule to never directly modify the state? Why does it work when calling the setState method? The reason is that react recalls the render method after changes have been made to the state through the setState method so setState is called in the relevant values in the component state change and once that's done setState triggers the render method calling it again. This is important because a render method that is returning different text based on the value of something in the state now has a chance to return something new based on the updated values in the state. It can control what should appear in the react app itself within the rendered methods. JSX but this doesn't work when the state is modified directly. It won't re-trigger the render and doesn't do anything beyond changing the values even though the values in the state object would be different. The render method won't notice this. Therefore the application appearance won't update based on the logic in your render method. OK let's explore this rule further by looking at some code. Head back to the portfolio application head to your toggleDisplayBio method and let's comment out the current valid setState call. And instead we're gonna do a direct modification of the state by setting a state value to a completely new value. So this.state.displayBio is going to be equal to a bang operator of not this.state.display bio. All right go ahead and save this. If you don't have the application running in the background already fire npm run start on the command line in the portfolio app. So in the command line fire npm run start. You'll also see that react app is equipped to give you a warning of not to modify state directly. But let's also look at the application in the browser and verify this ourselves and see what happens. And now that the toggleDisplayBio method has been refactored, let's try to click the read more button. And this time nothing happens. If you open the console you'll find that same warning that you shouldn't directly modify the state. So that's pretty helpful. So let's restore the method back to its valid form by putting back in that commented out line where we set the state of displayBio to a completely new value that is the result of calling the bang operator on the current this.state.displayBio method you click readMore and showLess now it should be working just as it did before. Cool! Now, overall this relates to another slightly confusing aspect of react. And this has to do with how we set up the onClick handlers one question you may have lingering is why are referring to only the method name itself. Within the onClick handler, rather than calling it for example doesn't it make sense to invoke toggleDisplayBio on line just like this by having a pair of parentheses to actually call the method now. If you save this, when you do, the change immediately leads to an error where the maximum call depth is going to be exceeded in the application. So we're exceeding the number of calls at the react engine can handle. This is because when the render function fires it will now fire toggleDisplayBio right away as soon as it gets to this line. Since we're calling the method itself because we've added the parentheses to invoke the function but within toggleDisplayBio recalling setState this changes the displayBio value. But again recall that setState triggers the render method once it's done so after this.state is done it's going to go back in the render method and once again it's going to call toggleDisplayBio a once more. Which goes back up to the toggleDisplay bar method which calls red state. Again this triggers a render it goes to the toggleDisplay file and now we get to this loop of setState and toggleDisplayBio and render method calls so by giving the onClick handlers only the function name the react engine under the hood knows that it should invoke the method only when the onClick is fired and not when it's actually crossed in the render method. Which is why when you go back to the original code without the parentheses things will be working just as before. All right, so we now had two very big conclusions from this overall exploration. One: the react rule of never modifying state. The main one is that you should use setState instead of a direct modification. And the second con- clusion is that handlers like onClick should be given function names because of the very fact that setState triggers a render call. OK let's move on and explore class properties and initializers which is a javascript syntax which can provide for us a cleaner way to declare the state and add methods to the component.