reactjsreact-ref

What does passing a ref to an element component do in React?


I always assumed refs in React were one-directional references. In other words, I thought that if I did:

const SomeComponent = () => {
  const ref = useRef();
  return <span ref={ref}>abc</span>
}

the ref wouldn't have any impact on the <span> at all; it would just let SomeComponent access the <span>'s DOM element.

However, I recently discovered that's not the case: the ref can actually impact the element it's passed in to. In a slight variation of the above, where I have the ref passed in:

const SomeComponent = forwardRef((props, ref) => {
  return <span ref={ref}>abc</span>
});

The passed-in ref can actually make React not render the child ('abc' in my example) of the <span>. Everything works as normal (there are no errors), but it renders as <span></span>.

What does passing a ref into a component actually do to the component itself? In particular, how could what the ref contains impact the rendering of the component?

I've tried reading the React docs, but they don't seem to cover this, so I came here.


Solution

  • what does passing a ref into a component actually do to the component itself?

    If you pass in a ref object (an object with a .current property), then react will assign the dom element to .current and do nothing else.

    If you pass in a ref function, then react will call that function and pass in the dom element. In principal this function could do anything, so if you write a weird function, you can wipe out the contents of the element. But most commonly, you'll just assign the element to some property of some object, much like what react did automatically with the ref object.

    In particular, how could what the ref contains impact the rendering of the component?

    The only way it would do that is if you write code that changes the element. Out of the box a ref is completely passive.