React-Hooks Cheatsheet

useRef

useRef

useRef 🌂

Notes

  • returns a 'ref' object.
  • Call signature: const refContainer = useRef(initialValueToBePersisted)
  • Value is persisted in the refContainer.current property.
  • values are accessed from the .current property of the returned object.
  • The.current property could be initialised to an initial value e.g. useRef(initialValue)
  • The object is persisted for the entire lifetime of the component.
  • View the docs.

Accessing the DOM

Instance Like Variables (Generic Container)

Other than just holding DOM refs, the "ref" object can hold any value.

You could do the same as storing the return value from a setInterval for cleanup.

function TimerWithRefID() {
const setIntervalRef = useRef();
useEffect(() => {
const intervalID = setInterval(() => {
// something to be done every 100ms
}, 100);
// this is where the interval ID is saved in the ref object
setIntervalRef.current = intervalID;
return () => {
clearInterval(setIntervalRef.current);
};
});
}
Edit this page on GitHub