InterviewHubPRO
Section Overview
Q274

Question 274 of 445

Part 9: React Hooks Deep Dive (262 - 316)

62%
React & Modern Frontend (445 Qs)•Part 9: React Hooks Deep Dive (262 - 316)

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.

js
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:

js
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.
js
 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>;
 }