Skip to content

Instantly share code, notes, and snippets.

@itaditya
Created August 10, 2021 09:58
Show Gist options
  • Save itaditya/1d5ee74654f85e4705940dd587146f28 to your computer and use it in GitHub Desktop.
Save itaditya/1d5ee74654f85e4705940dd587146f28 to your computer and use it in GitHub Desktop.
Explain Stale closures and how we can fix it.
const { useEffect } = require("react");
// Suffers from Stale Closures
export function useUpdatedExit(props) {
// initial = 0, latest = 0
// initial = 0, latest = 1
// initial = 0, latest = 2
const { initial, latest, cb } = props;
function handleExit() {
// initial = 0, latest = 0
if (initial !== latest) {
cb();
}
}
useEffect(() => {
// initial = 0, latest = 0
return () => {
// initial = 0, latest = 0
handleExit();
}
}, []);
}
// Using Ref to work-around Stale Closures
export function useUpdatedExit(props) {
// initial = 0, latest = 0
// initial = 0, latest = 1
// initial = 0, latest = 2
const { initial, latest, cb } = props;
const latestHandlerRef = useRef();
function handleExit() {
// initial = 0, latest = 2
if (latest !== initial) {
cb(latest);
}
}
useEffect(() => {
latestHandlerRef.current = handleExit;
});
useEffect(() => {
// initial = 0, latest = 0
return () => {
// initial = 0, latest = 0
latestHandlerRef.current();
}
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment