DEV Community

Discussion on: 3 React Mistakes Junior Developers Make With Component State

Collapse
 
thawkin3 profile image
Tyler Hawkins

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?

Collapse
 
c_v_ya profile image
Constantine

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

Thread Thread
 
thawkin3 profile image
Tyler Hawkins

Sure thing!

Collapse
 
thawkin3 profile image
Tyler Hawkins

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.