23

I'm aware that ref is a mutable container so it should not be listed in useEffect's dependencies, however ref.current could be a changing value.

When a ref is used to store a DOM element like <div ref={ref}>, and when I develop a custom hook that relies on that element, to suppose ref.current can change over time if a component returns conditionally like:

const Foo = ({inline}) => {
  const ref = useRef(null);
  return inline ? <span ref={ref} /> : <div ref={ref} />;
};

Is it safe that my custom effect receiving a ref object and use ref.current as a dependency?

const useFoo = ref => {
  useEffect(
    () => {
      const element = ref.current;
      // Maybe observe the resize of element
    },
    [ref.current]
  );
};

I've read this comment saying ref should be used in useEffect, but I can't figure out any case where ref.current is changed but an effect will not trigger.

As that issue suggested, I should use a callback ref, but a ref as argument is very friendly to integrate multiple hooks:

const ref = useRef(null);
useFoo(ref);
useBar(ref);

While callback refs are harder to use since users are enforced to compose them:

const fooRef = useFoo();
const barRef = useBar();
const ref = element => {
  fooRef(element);
  barRef(element);
};

<div ref={ref} />

This is why I'm asking whether it is safe to use ref.current in useEffect.

otakustay
  • 9,671
  • 3
  • 31
  • 42

2 Answers2

24

It doesn't safe because mutating the reference won't trigger a render, therefore, won't trigger the useEffect.

React Hook useEffect has an unnecessary dependency: 'ref.current'. Either exclude it or remove the dependency array. Mutable values like 'ref.current' aren't valid dependencies because mutating them doesn't re-render the component. (react-hooks/exhaustive-deps)

An anti-pattern example:

const Foo = () => {
  const [, render] = useReducer(p => !p, false);
  const ref = useRef(0);

  const onClickRender = () => {
    ref.current += 1;
    render();
  };

  const onClickNoRender = () => {
    ref.current += 1;
  };

  useEffect(() => {
    console.log('ref changed');
  }, [ref.current]);

  return (
    <>
      <button onClick={onClickRender}>Render</button>
      <button onClick={onClickNoRender}>No Render</button>
    </>
  );
};

Edit xenodochial-snowflake-hhgr6


A real life use case related to this pattern is when we want to have a persistent reference, even when the element unmounts.

Check the next example where we can't persist with element sizing when it unmounts. We will try to use useRef with useEffect combo as above, but it won't work.

// BAD EXAMPLE, SEE SOLUTION BELOW
const Component = () => {
  const ref = useRef();

  const [isMounted, toggle] = useReducer((p) => !p, true);
  const [elementRect, setElementRect] = useState();

  useEffect(() => {
    console.log(ref.current);
    setElementRect(ref.current?.getBoundingClientRect());
  }, [ref.current]);

  return (
    <>
      {isMounted && <div ref={ref}>Example</div>}
      <button onClick={toggle}>Toggle</button>
      <pre>{JSON.stringify(elementRect, null, 2)}</pre>
    </>
  );
};

Edit Bad-Example, Ref does not handle unmount


Surprisingly, to fix it we need to handle the node directly while memoizing the function with useCallback:

// GOOD EXAMPLE
const Component = () => {
  const [isMounted, toggle] = useReducer((p) => !p, true);
  const [elementRect, setElementRect] = useState();

  const handleRect = useCallback((node) => {
    setElementRect(node?.getBoundingClientRect());
  }, []);

  return (
    <>
      {isMounted && <div ref={handleRect}>Example</div>}
      <button onClick={toggle}>Toggle</button>
      <pre>{JSON.stringify(elementRect, null, 2)}</pre>
    </>
  );
};

Edit Good example, handle the node directly

Dennis Vash
  • 31,365
  • 5
  • 46
  • 76
  • In case a ref is passed to a DOM element, I think every DOM change is caused by a render, and an effect should trigger after a render is committed beginning with comparing `ref.current`, is it possible to still miss some ref updates when it is only used to reference a DOM? – otakustay Mar 01 '20 at 15:41
  • Do you have an example of such case? (it wont trigger render) – Dennis Vash Mar 01 '20 at 15:52
  • I can't have an example where DOM change won't trigger a render so I'm wondering why it is unsafe to use DOM ref.current in useEffect – otakustay Mar 02 '20 at 05:16
  • @otakustay If you relaying on DOM change why you using a dep array? Put the logic in useEffect without a dep array. ref.current as dependency is useless as mentioned in the answer – Dennis Vash Mar 02 '20 at 07:18
  • 2
    Because ref can be changed form div to span, or from null to div across multiple renders, but empty deps array can run effect only once on the first mounted DOM element. – otakustay Mar 04 '20 at 04:19
0

I faced a similar problem wherein my ESLint complained about ref.current usage inside a useCallback. I added a custom hook to my project to circumvent this eslint warning. It toggles a variable to force re-computation of the useCallback whenever ref object changes.

import { RefObject, useCallback, useRef, useState } from "react";

/**
 * This hook can be used when using ref inside useCallbacks
 * 
 * Usage
 * ```ts
 * const [toggle, refCallback, myRef] = useRefWithCallback<HTMLSpanElement>();
 * const onClick = useCallback(() => {
    if (myRef.current) {
      myRef.current.scrollIntoView({ behavior: "smooth" });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [toggle]);
  return (<span ref={refCallback} />);
  ```
 * @returns 
 */
function useRefWithCallback<T extends HTMLSpanElement | HTMLDivElement | HTMLParagraphElement>(): [
  boolean,
  (node: any) => void,
  RefObject<T>
] {
  const ref = useRef<T | null>(null);
  const [toggle, setToggle] = useState(false);
  const refCallback = useCallback(node => {
    ref.current = node;
    setToggle(val => !val);
  }, []);

  return [toggle, refCallback, ref];
}

export default useRefWithCallback;
jarora
  • 4,400
  • 2
  • 30
  • 39