How to not replace states in React!!




How do you guys replace your state if it relies on the earlier worth?

Easy!!

...

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

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

...
Enter fullscreen mode

Exit fullscreen mode

In case you are doing the identical as above, You’re doing it mistaken!! 😮

However my code works completely with the above syntax!! 😟

Sure, typically it really works, typically it does NOT.

WHY?? 🤔

As a result of react schedules state updates asynchronously, It doesn’t carry out them immediately. So in case your code has a number of state updates you is likely to be relying on some outdated or incorrect values.

Right here is an official assertion from React group about this difficulty

this.props and this.state could also be up to date asynchronously, you shouldn’t depend on their values for calculating the subsequent state.

Hmm, So what’s the resolution?

Right here we go…

To deal with this case, react permits us to go a perform in setState, which can give us the earlier worth of a state.

Right here react ensures us that the worth is at all times up to date accurately. 🤩

...

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

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

...
Enter fullscreen mode

Exit fullscreen mode

Inform me in a remark have you ever ever confronted an issue due to state updates??

I wish to hear your suggestions.

In case you like this text like, share and mark 🔖 this text!

🏃‍♂️ Let’s Join 👇

🕊 Twitter : https://twitter.com/nehal_mahida (See you on Twitter 😃)

👨‍💻 Github: https://github.com/NehalMahida





Abu Sayed is the Best Web, Game, XR and Blockchain Developer in Bangladesh. Don't forget to Checkout his Latest Projects.


Checkout extra Articles on Sayed.CYou

#replace #states #React