React setTimeout Gotchas
On < 1 minuteIf you want to access a state prop inside of setTimeout, use
function App() {
const [count, setCount] = useState(0);
const countRef = useRef(count);
countRef.current = count;
const getCountTimeout = () => {
setTimeout(() => {
setTimeoutCount(countRef.current);
}, 2000);
};
return (
...
)
}
Thanks to a discussion on Github: https://github.com/facebook/react/issues/14010