cft

React useState hook is asynchronous!

React useState hook is asynchronous, but what does that mean? It means that useState hook will not update the state immediately.


user

Mohammed Nadeem Shareef

2 years ago | 2 min read

Hello Developers 👋

I would like to share something I recently got to know, so the background is, in my project I was using useState value right after updating it and I was getting previous value(not updated value) and to my surprise, I found out that useState hook is asynchronous

what it is?

Basically, the thing is you don't get update value right after updating state.

What is the workaround/solution?

We can use the useEffect hook and add our state in the dependence array, and we will always get the updated value.

Show me the code 🤩🤩🤩

import { useState } from "react";

export default function CountWithoutEffect() {
const [count, setCount] = useState(0);
const [doubleCount, setDoubleCount] = useState(count * 2);
const handleCount = () => {
setCount(count + 1);
setDoubleCount(count * 2); // This will not use the latest value of count
};
return (
<div className="App">
<div>
<h2>Count Without useEffect</h2>
<h3>Count: {count}</h3>
<h3>Count * 2: {doubleCount}</h3>
<button onClick={handleCount}>Count++</button>
</div>
</div>
);
}

  • Here we have a very simple and straight forward component.
  • On button click, we are updating two states and one state is dependent on other states.
  • The doubleCount will be one step behind the count.
  • Check out the Live Demo

Solving this issue 🧐🧐🧐

This can be easily solved with useEffect hook, let's see the code

import { useState, useEffect } from "react";

export default function CountWithEffect() {
const [count, setCount] = useState(0);
const [doubleCount, setDoubleCount] = useState(count * 2);
const handleCount = () => {
setCount(count + 1);
};

useEffect(() => {
setDoubleCount(count * 2); // This will always use latest value of count
}, [count]);

return (
<div>
<h2>Count with useEffect</h2>
<h3>Count: {count}</h3>
<h3>Count * 2: {doubleCount}</h3>
<button onClick={handleCount}>Count++</button>
</div>
);
}

  • Here, whenever count changes we are updating doubleCount
  • Check out the live Demo

Closing here 👋👋👋

This is Shareef.
Live demo
GitHub repo of this blog
Stackover flow link for more info
My 
Portfolio
Twitter 
ShareefBhai99
Linkedin
My 
other Blogs

Upvote


user
Created by

Mohammed Nadeem Shareef

Hello. I am a FrontEnd Developer I work with reactJS, nextJS, TypeScript, firebase, tailwindcss, SCSS.


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles