re: 3 React Mistakes Junior Developers Make With Component State VIEW POST

re: I'm completely new to React so thank you for the explanations! And how to do things properly. But I have a question if you would be so kind to repl...

Good question! I should clarify my article to help explain that better.

You should use a function of the previous state when you are updating the state that relies on the previous state. So like in the two examples I gave, enabling/disabling a button relies on the previous state of whether or not is was disabled. And incrementing a counter relies on the previous value of the counter.

If you aren't relying on the previous state but are just setting an entirely new value, then using an object as an argument is perfectly fine. For example, if you were fetching a list of users from the server and then needed to store that list of users in the component's state, it would be perfectly fine to do something like:

this.setState({ users: fetchedUserDataHere })

Because in that case it doesn't matter what the previous value of users was before. You just want to store the new data you just fetched.

Does that help?


Yes, I think I get it now. Thank you one more time! 😄


As an update, I updated the article just now to hopefully be more clear.

I changed the header text to:

Setting state that relies on the previous state without using a function

And I added this paragraph at the end of the section:

The key here is that if your new state relies on the value of the old state, you should always use a function as the argument. If you are setting a value that does not rely on the value of the old state, then you can use an object as the argument.

code of conduct - report abuse