ReactNext.jsError Fix2026 Updated
React useState Not Updating Immediately— Fixed [2026]
Also covers: stale closures · state batching · object state not updating
January 20265 min readReact 18 · Next.js
⚡ Key Rule — State Updates Are Async
component.jsx
const [count, setCount] = useState(0)
// ❌ WRONG — count is still 0 here, not 1
setCount(count + 1)
console.log(count) // prints 0
// ✅ CORRECT — read new value in useEffect
useEffect(() => {
console.log('Updated count:', count) // prints 1 after re-render
}, [count])Why useState Does Not Update Immediately
React state updates are asynchronous and batched. When you call setState, React schedules a re-render for the next tick. The state variable in your current render is immutable — it will always hold the value from when that render started. The new value is only available in the next render cycle.
12 min
Never Read State Right After Setting It
The most common mistakeCounter.jsx
import { useState, useEffect } from 'react'
export default function Counter() {
const [count, setCount] = useState(0)
function handleClick() {
setCount(count + 1)
// ❌ WRONG — still reads old value
console.log(count) // 0, not 1
// ✅ CORRECT — use a local variable if you need the new value now
const newCount = count + 1
setCount(newCount)
console.log(newCount) // 1
}
// ✅ CORRECT — react to state changes with useEffect
useEffect(() => {
console.log('Count changed to:', count)
}, [count])
return <button onClick={handleClick}>Count: {count}</button>
}22 min
Functional Update for Derived State
Stale state in event handlers and async codeWhen new state depends on old state — especially in async code — always use the functional update form to get the latest value.
component.jsx
// ❌ WRONG — count may be stale in async handlers
async function handleAsyncOperation() {
await doSomething()
setCount(count + 1) // 'count' is from when the handler was created
}
// ✅ CORRECT — functional update always gets latest state
async function handleAsyncOperation() {
await doSomething()
setCount(prev => prev + 1) // 'prev' is always the latest value
}
// ✅ Also correct for multiple updates in one handler
function handleTripleClick() {
// ❌ This only increments once — all three reads see count=0
setCount(count + 1)
setCount(count + 1)
setCount(count + 1)
// ✅ This increments three times
setCount(prev => prev + 1)
setCount(prev => prev + 1)
setCount(prev => prev + 1)
}33 min
Fix Stale Closures in useEffect
useEffect reading old state valueTimer.jsx
import { useState, useEffect, useRef } from 'react'
// ❌ WRONG — stale closure: count is always 0 inside the interval
function BadTimer() {
const [count, setCount] = useState(0)
useEffect(() => {
const id = setInterval(() => {
setCount(count + 1) // 'count' captured as 0 at effect creation
}, 1000)
return () => clearInterval(id)
}, []) // ← missing count in deps → stale closure
}
// ✅ CORRECT — functional update avoids stale closure
function GoodTimer() {
const [count, setCount] = useState(0)
useEffect(() => {
const id = setInterval(() => {
setCount(prev => prev + 1) // always gets latest value
}, 1000)
return () => clearInterval(id)
}, []) // no deps needed with functional update
}42 min
Object and Array State Updates
State object not updating — must spreadForm.jsx
// ❌ WRONG — mutating object does not trigger re-render
const [user, setUser] = useState({ name: '', email: '' })
user.name = 'John' // React cannot detect this mutation
setUser(user) // same reference → no re-render
// ✅ CORRECT — create a new object with spread
setUser(prev => ({ ...prev, name: 'John' }))
// ✅ Array state — always create new array
const [items, setItems] = useState([])
setItems(prev => [...prev, newItem]) // add
setItems(prev => prev.filter(i => i.id !== id)) // remove
setItems(prev => prev.map(i => i.id === id ? { ...i, done: true } : i)) // update52 min
Use useRef for Values That Don't Need Re-render
Value changes but component should not re-renderStopWatch.jsx
import { useState, useRef } from 'react'
export default function Stopwatch() {
const [elapsed, setElapsed] = useState(0)
const intervalRef = useRef(null) // ← ref for the interval ID
function start() {
// useRef — not useState — because changing it should not re-render
intervalRef.current = setInterval(() => {
setElapsed(prev => prev + 1)
}, 1000)
}
function stop() {
clearInterval(intervalRef.current) // read synchronously — always current
}
return (
<div>
<p>{elapsed}s</p>
<button onClick={start}>Start</button>
<button onClick={stop}>Stop</button>
</div>
)
}Prevention
- Never read state immediately after setting it in the same handler
- Use functional updates (prev => prev + 1) whenever new state depends on old state
- Add all state variables read inside useEffect to the dependency array
- Spread objects and arrays when updating: setUser(prev => ({ ...prev, name }))
- Use useRef for values that change but should not trigger re-renders
Frequently Asked Questions
Why is useState not updating immediately in React?+−
useState updates are asynchronous and batched. When you call setState, React schedules a re-render but does not update the variable immediately. The new value is only available in the next render. To read state after setting it, use useEffect with the state variable as a dependency.
How do I get the updated state value right after setState?+−
You cannot read state immediately after setting it in the same event handler. Use useEffect with the state as a dependency to react to changes: useEffect(() => { console.log('New value:', count) }, [count])
React state update not working in async function — why?+−
State updates work the same in async functions. The issue is usually a stale closure — the async function captured the old state value when it was created. Use the functional update form: setState(prev => prev + 1) instead of setState(state + 1).
How do I update an object in useState?+−
Always spread the existing state: setUser(prev => ({ ...prev, name: 'John' })). Never mutate the object directly — React uses reference equality to detect changes, and mutating the object without creating a new one will not trigger a re-render.
What is a stale closure in React?+−
A stale closure is when a function (like a useEffect callback or event handler) captures a state variable from a previous render. When that function runs, it uses the old value. Fix by adding the variable to the useEffect dependency array, or use the functional update form of setState.
When should I use useRef instead of useState?+−
Use useRef when you need to store a value that: 1) should not trigger a re-render when it changes, 2) needs to be read synchronously inside event handlers, or 3) persists across renders (like a DOM ref or a timer ID). Common examples: scroll position, previous values, interval IDs.
Need Expert Help?
We Build Production-Grade Next.js Apps
Softplix builds full-stack applications. Dealing with complex React state management? We can help.
Talk to an Engineer