function Counter() {
const [count, setCount] = useState(0);
const savedCallback = useRef(null);
function callback() {
setCount(count + 1);
}
useEffect(() => {
savedCallback.current = callback;
});
useEffect(() => {
function tick() {
savedCallback.current();
}
let id = setInterval(tick, 1000);
return () => clearInterval(id);
}, []);
return <h1>{count}</h1>;
}```
When the component mounts, the second `useEffect` is run first. But shouldn't `savedCallback.current` be `null` since the first `useEffect` hasn't run yet?
#Why is savedCallback.current !== null?
13 messages · Page 1 of 1 (latest)
Why do you think the second useEffect is run first? Hint: it isn't. The first useEffect has absolutely already run prior to the second one. They're run in the order of the source code.
I thought the second one was run on mount, and the first is run after render
Thank you though :)
Oh wait but the first will also be run on mount
I forgot that
Correct. Hence they're run in order 🙃
And to be very specific both run after first render. But the second won't run on re-renders.
Oh really? Neither of them after mount and before render?
That's nice to know
Correct.
I remember reading that somewhere before actually, it's hard to remember everything 😅