How not to update states in React!!

nehal_mahida

Nehal Mahida

Posted on October 23, 2021

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.โ˜•

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
nehal_mahida
Nehal Mahida

Posted on October 23, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About