Don’t Make This Common Mistake with React State

Ravi Sharma
Bits and Pieces
Published in
2 min readOct 29, 2021

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.

Give it a try →

Learn more

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Published in Bits and Pieces

Insightful articles, step-by-step tutorials, and the latest news on full-stack composable software development

No responses yet

What are your thoughts?