Don’t Make This Common Mistake with React State
I have often seen one common mistakes being made by some beginner React devs which is to update React state.
How do you update your state if it depends on the previous value? If you are following the below method to update React state then you are doing it wrong!
const [counter, setCounter] = useState(0);
const updateCounter = () => {
setCounter( counter + 1 );
}
Although the above method will work, this may not be the best approach.
In the official React documentation, they mention: "this.props
and this.state
may be updated asynchronously, you should not rely on their values for calculating the next state.”
So what is the best approach?
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;
});
}
Please tell me in a comment have you ever faced any problem because of state updates? I would like to hear your feedback.
Thank you for reading!
You can visit my YouTube channel “JavaScript Centric” and subscribe it for interesting videos.
Build composable web applications
Don’t build web monoliths. Use Bit to create and compose decoupled software components — in your favourite frameworks like React or Node. Build scalable and modular applications with a powerful and enjoyable dev experience.
Bring your team to Bit Cloud to host and collaborate on components together, and speed up, scale, and standardize development as a team. Try composable frontends with a Design System or Micro Frontends, or explore the composable backend with serverside components.