5

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 argument.

Given this react hook component:

const myComponent = ({ ...props}) => {
  const myRef = React.useRef(null);

  ...

  return (
    <div>
      ref={myRef}
    </div>
  )
}

versus

const myComponent = ({ ...props}) => {
  const myRef = React.useRef(null);

  ...

  return (
    <div>
      ref={element => {
        myRef.current = element;        
      }}
    </div>
  )
}

2 Answers 2

2

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

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

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

  return (
    <>
      <h1 ref={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.

0

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 :

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

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.