#Why is savedCallback.current !== null?

13 messages · Page 1 of 1 (latest)

dense arch
#
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?
haughty patio
dense arch
#

Thank you though :)

#

Oh wait but the first will also be run on mount

#

I forgot that

haughty patio
#

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.

dense arch
#

That's nice to know

dense arch
#

I remember reading that somewhere before actually, it's hard to remember everything 😅