𝗙𝗶𝘅 𝗦𝘁𝗮𝗹𝗲 𝗖𝗹𝗼𝘀𝘂𝗿𝗲𝘀 𝗶𝗻 𝗥𝗲𝗮𝗰𝘁 𝗛𝗼𝗼𝗸𝘀

You build a timer in a React useEffect hook. You want to auto-save a document every five seconds. The timer runs, but it saves an empty document. The user typed ten paragraphs, but the timer sees nothing.

This is a stale closure.

The useEffect hook captures variables from the first render. If you leave the state out of the dependency array, the timer stays stuck in the past. It uses an old version of your data.

If you add the state to the dependency array, the timer resets every time the user types a character. This ruins performance and breaks your timing logic.

You solve this with the Mutable Ref Pattern.

Use the useRef hook to hold your latest state. This allows your timer to access fresh data without triggering new renders or resetting the interval.

Follow these steps:

This approach decouples your timer from your data. Your background tasks stay stable. Your data stays accurate.

Stop losing user data to silent bugs. Use refs to keep your asynchronous tasks in sync with your UI.

Source: https://dev.to/iprajapatiparesh/escaping-the-trap-fixing-stale-closures-in-react-hooks-4gg7