Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
769 views
in Technique[技术] by (71.8m points)

reactjs - Is it safe to use ref.current as useEffect's dependency when ref points to a DOM element?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...