Today I Learned

Run cleanup logic conditionally

Running some logic conditionally on component unmount requires usage of useRef hook.

We cannot do:

useEffect(() => {
  return () => {
    if (status === "explanation") {
      console.log("Trigger logic");
    }
  };
}, []);

Because status coming from the useState hook would not be properly updated due to stale closure


We also cannot add status to dependency array

useEffect(() => {
  return () => {
    if (status === "explanation") {
      console.log("Trigger logic");
    }
  };
}, [status]);

Because the effect would be triggered every time the status changed (not only on unmount)


We need to useRef to smuggle the status value into useEffect without triggering it on status change.

  useEffect(() => {
    return () => {
      if (statusRef.current === "explanation") {
        console.log("Trigger logic");
      }
    };
  }, [statusRef]);

CodeSandbox example