DEV Community

Discussion on: Using refs in React.js

Collapse
 
jukkahuuskonen profile image
Jukka Huuskonen

This seems to discuss only refs to document elements. You left out the other half of useRef-usage: when you need to have variables in eg. useEffects-hook that may change during effects lifespan, but you don't want to re-run the hook when that value changes. Good example is when you want to do something when the component unmounts.

const valueAtUnmountRef = useRef();

  useEffect(() => {
    yourFunctionToRunOnUnmount(valueAtUnmountRef.current);
  }, []);
Enter fullscreen mode Exit fullscreen mode

Now in components lifetime, you can update the valueAtUnmountRef.current and be assured that yourFunctionToRunOnUnmount has correct value as parameter when component unmounts.

Collapse
 
amoled27 profile image
Amod Shinde

Thanks a lot for contributing to my knowledege \m/