DEV Community

Discussion on: useRef helps you to avoid re-rendering of the component

Collapse
 
merri profile image
Vesa Piittinen

Maybe this is mindblowing to someone:

function Component(props) {
  // can also be: const latest = useRef(props).current;
  const [latest] = useState(props);
  Object.assign(latest, props);

  // stable never changing callbacks that take `latest` as dependency
  const { hello, world } = useMemo(() => {
    function hello() {
      if (latest.active) latest.onClick();
    }

    function world() {
      if (latest.disabled) latest.onLifeHack();
    }

    return { hello, world };
  }, [latest]);

  return <div data-whatever />;
}
Enter fullscreen mode Exit fullscreen mode

The benefit: as latest never changes (it always has the same object reference) you still do get access to the latest props. This pattern can be easier than writing a bunch of useCallback, especially if all of the callbacks can remain stable.

Sometimes it can also be useful that the callback changes when props change, but usually when dealing with things like event handlers you just want the latest prop without mutating the rendered callback that is already in DOM.