DEV Community

Cover image for How not to update states in React!!
Nehal Mahida
Nehal Mahida

Posted on • Updated on

How not to update states in React!!

How do you guys update your state if it depends on the previous value?

Simple!!

...

const [counter, setCounter] = useState(0);

const updateCounter = () => {
  setCounter( counter + 1 );
}

...
Enter fullscreen mode Exit fullscreen mode

If you are doing the same as above, You are doing it wrong!! ๐Ÿ˜ฎ

But my code works perfectly with the above syntax!! ๐Ÿ˜Ÿ

Yes, sometimes it works, sometimes it does NOT.

WHY?? ๐Ÿค”

Because react schedules state updates asynchronously, It does not perform them instantly. So if your code has multiple state updates you might be depending on some outdated or incorrect values.

Here is an official statement from React team about this issue

this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

Hmm, So what is the solution?

Here we go...

To handle this situation, react allows us to pass a function in setState, which will give us the previous value of a state.

Here react guarantees us that the value is always updated correctly. ๐Ÿคฉ

...

const [counter, setCounter] = useState(0);

const updateCounter = () => {
  setCounter((prevState) => {
    // some logic 
    return prevState + 1; 
  });
}

...
Enter fullscreen mode Exit fullscreen mode

Tell me in a comment have you ever faced a problem because of state updates??

I would like to hear your feedback.

If you like this article like, share and mark ๐Ÿ”– this article!

๐Ÿƒโ€โ™‚๏ธ Let's Connect ๐Ÿ‘‡

๐Ÿ•Š Twitter : https://twitter.com/nehal_mahida (See you on Twitter ๐Ÿ˜ƒ)

๐Ÿ‘จโ€๐Ÿ’ป Github: https://github.com/NehalMahida

Support ๐Ÿค—

If you are enjoying my articles, consider supporting me with a coffee.โ˜•

Discussion (17)

Collapse
lukeshiru profile image
LUKESHIRU

The first one is fine for the vast majority of scenarios, and you should use it, so that title "How not to update states in React" is wrong. A more fitting title would be "How to update states in React with async operations" or something like that.

The second example is only useful if you need to know the previous value of the state, instead of the current, which generally is if you're updating the state asynchronously or from some scheduler like setInterval, setTimeout or requestAnimationFrame.

As you mentioned, the state updates are scheduled, not ran in place, so the value of the state will not be changed until next render. One pretty common mistake folks do is they want to update the same state several times in the same render, so they might do something like this:

const [count, setCount] = useState(0);

// In some callback:
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
Enter fullscreen mode Exit fullscreen mode

And then they realize that instead of having 3, they just have 1 ... so they might fall into the mistake of using the callback to "resolve" the issue:

setCount(prevCount => prevCount + 1);
setCount(prevCount => prevCount + 1);
setCount(prevCount => prevCount + 1);
Enter fullscreen mode Exit fullscreen mode

Yey! They got 3.... but the actual correct approach for scenarios like this, is to set the value once you actually are sure of it, instead of scheduling 3 state changes:

let totalCount = count;
totalCount += 1;
totalCount += 1;
totalCount += 1;
setCount(totalCount);
Enter fullscreen mode Exit fullscreen mode

Obviously this example is ridiculous, but is only to illustrate that if you need to do several changes in the same state, you should do them before you set the state, in a temporary variable if necessary.

Cheers!

Collapse
nehal_mahida profile image
Nehal Mahida Author

Thanks, man, You put great points ๐Ÿ™๐Ÿป

Trust me it adds value to my post.

Regarding the title, Yes the first approach works most of the time.
But don't you think if programmers follow the second approach from starting itself, they don't need to worry about state updates ( asynchronous or synchronous) at the end?

As the world moves towards pair or group programming it is a good habit to make a RIGHT approach a default one. ๐Ÿค—

Happy Coding!!

Collapse
lukeshiru profile image
LUKESHIRU

As I mentioned in my initial comment, the problem with the second approach is that you're scheduling more state changes (so you're making React do more work than what it should). The idea with having the value and the callback options is that you should use the one that does the job correctly, not use "always the same". The rule is simple: Do you need the current state? Use the value approach. Do you need the past state or are you running outside React's scheduler? Use the callback.

I would even dare to say that usually the callback approach is a "code smell", because we actually need to use it in extremely particular scenarios.

Thread Thread
nehal_mahida profile image
Nehal Mahida Author

You are right. My article is all about when you need the previous value of the state then and then you need to use the callback function in setState otherwise it's fine.

Collapse
andresausecha profile image
Andres Ausecha Mosquera

Usually the first one works fine, but sometimes when you have a state that updates very frequently the second one is the correct. Good post

Collapse
nehal_mahida profile image
Nehal Mahida Author

Thanks, glad you like it. ๐Ÿค—
It means a lot ๐Ÿ™๐Ÿป

Collapse
rehanpia profile image
Rehan Zaheer Zaheer ahmed

I want to connect web3 with react. Can u provide me a better guide to interect from react to a solidity smart contract through web3. Thank u

Collapse
nehal_mahida profile image
Nehal Mahida Author

For web3, I may not be the right person to ask but I can connect you with people who are good at it.

@vittostack @oliverjumpertz are the best to ask for ๐Ÿ˜ƒ

Collapse
rehanpia profile image
Rehan Zaheer Zaheer ahmed

Thank you

Collapse
itscasey profile image
Casey ๐Ÿ’Ž

Check out buildspace.so - they have cohort projects AND open source material, so you can skip the wait and just review their info in their repos

Collapse
nehal_mahida profile image
Nehal Mahida Author

Thanks for sharing, I hope it helps @rehanpia

Collapse
jafb321 profile image
Jose Antonio Felix

Thank you for the info Man! I didnt know this useState Hook situation

Collapse
nehal_mahida profile image
Nehal Mahida Author

I'm glad you like it ๐Ÿค—

Let's spread the knowlege. ๐Ÿš€

Happy Coding!!

Collapse
gustavovinife profile image
Gustavo Vinicius

Thanks for the post! Sometimes we forgot this small things in our code, then we got a big unperformed and not stable codebase.

Collapse
nehal_mahida profile image
Nehal Mahida Author

Purpose served ๐Ÿ™๐Ÿป

Collapse
belidenikhil profile image
NikhilBelide

Great article buddy

Collapse
nehal_mahida profile image
Nehal Mahida Author

Glad you like it! ๐Ÿค—