Difference between using forwardRef or just passing ref as a prop in React and its effect on useImperitaveHandle

Viewed 232

The React docs provides the following example for forwardRef

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;

But this piece of code when the ref is passed as a prop as opposed to passing it via ForwardRef also works

const FancyButton = (props) => (
  <button ref={props.testRef} className="FancyButton">
    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton testRef={ref}>Click me!</FancyButton>;

If both these work the same way, what is the reason for using ForwardRef?

Also can useImperitaveHandle Hook also be used when the ref is passed as a prop?

0 Answers
Related