2

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?

dracarys
  • 1,071
  • 1
  • 15
  • 31
  • 1
    Please have a look at [value of using React.forwardRef vs custom ref prop](https://stackoverflow.com/questions/58578570/value-of-using-react-forwardref-vs-custom-ref-prop) as well as [When to use useImperativeHandle, useLayoutEffect, and useDebugValue](https://stackoverflow.com/questions/57005663/when-to-use-useimperativehandle-uselayouteffect-and-usedebugvalue). – usafder Nov 07 '20 at 14:21

0 Answers0