Facebook Pixel

Is dispatch from useReducer stable across renders in React?

Yes. dispatch has a stable identity (it does not change between renders). So a callback that uses dispatch (not state directly) does not have a stale closure problem. This is why useReducer is a good fix for complex state in intervals.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Closures and React: Stale Closures Explained

A callback (in useEffect, setInterval, etc.) that captures state from a previous render, not the current one. When the state updates in later renders, the old callback still sees the old value, causing bugs.

Use the functional form of setState (setCount(c => c + 1)) which receives the latest state. Or add the state to the useEffect dependency array. Or use useRef to hold the latest value. Or use useReducer (dispatch is stable).

Because the setInterval callback closes over count from the render when useEffect ran (usually the first render, count = 0). Each tick calls setCount(0 + 1), so count stays at 1. Use setCount(c => c + 1) instead.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.