Skip to content Skip to sidebar Skip to footer

Difference Between Assigning React Ref Using A Callback Versus Setting It Directly?

It works and behaves the same, but wanted to know if there are any practical differences to setting a ref directly versus setting it via a callback that has the element as an argum

Solution 1:

Both are similar as per the useRef docs:

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue).

So, first example of code will work exactly like the second example of code.

Except

If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.

Meaning; if you want to re-render the component then you can use the callback ref.


Best example from the docs itself:

To measure the position or size of a DOM node

functionMeasureExample() {
  const [height, setHeight] = useState(0);

  const measuredRef = useCallback(node => {
    if (node !== null) {
      setHeight(node.getBoundingClientRect().height);
    }
  }, []);

  return (
    <><h1ref={measuredRef}>Hello, world</h1><h2>The above header is {Math.round(height)}px tall</h2></>
  );
}

So, you can find the height of the element will be changed by using callback ref. If you were not using callback ref, then it wouldn't have been re-rendered and no content height would have been updated.

Solution 2:

Well, with first approach you can't notify when its content changes, mutating the .current property will not re-render it, but using a callback ref you can run some code, based on your use-case, when React attaches or detaches a ref to a DOM node.

For the callback approach, you really don't need to use useRef instead you can use useCallback. here is an example from React documentation :

functionMeasureExample() {
  const [height, setHeight] = useState(0);

  const measuredRef = useCallback(node => {
  if (node !== null) {
     setHeight(node.getBoundingClientRect().height);
  }
  }, []);

    return (
   <><h1ref={measuredRef}>Hello, world</h1><h2>The above header is {Math.round(height)}px tall</h2></>
 );
}

Post a Comment for "Difference Between Assigning React Ref Using A Callback Versus Setting It Directly?"