Gilian
Gilian

Reputation: 1599

React useEffect cleanup only on dismount

I would like to trigger an alert on component dismount like so:

const [checked, setChecked] = useState(false);

useEffect(() => {
    return () => {
        if(checked) alert("Hi")
    };
}, []);

...

However, the effect doest update the checked state when it is changed. This can be fixed however when changing the dependencies from [] to [checked]. This, however, triggers the alert every render instead of on dismount. But I only want to trigger this on a dismount. How can this be done with react hooks?

Upvotes: 0

Views: 602

Answers (1)

lissitz
lissitz

Reputation: 546

You can store the latest value of checked in a ref and then access it from the useEffect.

  const [checked, setChecked] = useState(false);
  const checkedRef = useRef(checked);

  useEffect(() => {
    checkedRef.current = checked;
  }, [checked]);

  useEffect(() => {
    return () => {
      if (checkedRef.current) alert("Hi");
    };
  }, []);

Because refs don't trigger updates, the second useEffect will only run once, but the first useEffect will make sure checkedRef.current has the latest value.

Upvotes: 2

Related Questions