useRef()

The useRef hook provides a way to persist values across renders without causing re-renders when updated. It is useful for storing mutable references (e.g., DOM nodes, timers, or cached values) that should survive component updates.


Usage

module.exports = ({ useRef, useEffect, api }) => {
  const myRef = useRef(null);

  useEffect(() => {
    // Assign a value to the ref
    myRef.current = "Hello World";

    api.console.log("Ref value:", myRef.current);
  }, []);

  return <div>Check logs for ref value</div>;
};

Behavior

  • useRef(initialValue) returns an object with a .current property.

  • Updating myRef.current does not trigger a re-render.

  • The value stored in .current persists for the lifetime of the component.


When to Use

  • Keeping track of DOM elements or third-party library instances.

  • Storing values that need to persist but should not cause re-renders (e.g., counters, cache, timers).

  • Acting as an instance variable inside functional components.

Last updated