FrontendDeveloper.in

React question detail

Is useState Synchronous or Asynchronous?

The useState hook is synchronous, but state updates are asynchronous. When you call useState(), it runs synchronously and returns the state variable and setter function as tuple.

const [count, setCount] = useState(0);

This happens immediately during rendering. However, the state update function (setState) is asynchronous in the sense that it doesn't update the state immediately. React batches updates and applies them before the next render. You won’t see the updated value immediately after calling setState.

Example:

const [count, setCount] = useState(0);

function handleClick() {
setCount(count + 1);
console.log(count); // ❗️Still logs the old value
}

The > console.log(count) prints the old value, because the update hasn’t happened yet.

To see the updated state value, you can use useEffect() hook. It runs after the component has re-rendered.  By the time useEffect runs:

  • The component has been updated.
  • The state contains the new value.
import React, { useState, useEffect } from 'react';

function Counter() {
const [count, setCount] = useState(0);

const handleClick = () => {
setCount(count + 1);
console.log('Clicked count (old):', count); // Old value
};

useEffect(() => {
console.log('Updated count:', count); // New value
}, [count]); // Only runs when `count` changes

return <button onClick={handleClick}>Count: {count}</button>;
}
Back to all React questions
Get LinkedIn Premium at Rs 399