What is a stale closure in React, and how do you fix it?

React hooks and effects · Freshers and experienced

Model answer

A function created during a render keeps the values from that render. If an interval or event listener is set up once, it may keep reading an old state value. Fixes: use the updater form setCount((c) => c + 1), list the right dependencies so the effect re-subscribes, or store the latest value in a ref.

Learn this topic

React useEffect Explained: Side Effects, Dependencies and Cleanup in the course React.js Full Course: Beginner to Advanced.

Sign in to add your own answer.

More questions