2

Are there some benefits in using forwardRef over custom prop approach? One assumption that comes to a mind is that with forwardRef React won't try to serialize the passed element, but I'm pretty sure it will not serialize it in both cases. Am I right or wrong?

Custom prop approach:

import { useRef } from "react";

const ParentComponent = () => {
  const someRef = useRef(document.createElement("div"));

  return <ChildComponent somePropWithRef={someRef}/>;
}

const ChildComponent = ({somePropWithRef}) => {
  return <div>Ref is {somePropWithRef.current.nodeName}</div>
}

export default ParentComponent

Same with forwardRef:

import { useRef, forwardRef } from "react";

const ParentComponent = () => {
  const someRef = useRef(document.createElement("div"));

  return <ChildComponent ref={someRef}/>;
}

const ChildComponent = forwardRef((_, ref) => {
  return <div>Ref is {ref.current.nodeName}</div>
});

export default ParentComponent

Bonus question: will custom prop approach somehow affect the behavior of useImperativeHandle hook?

Shura
  • 507
  • 5
  • 8

0 Answers0