Created
August 10, 2021 09:58
-
-
Save itaditya/1d5ee74654f85e4705940dd587146f28 to your computer and use it in GitHub Desktop.
Explain Stale closures and how we can fix it.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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