0

I can find multiple examples/docs explaining how we can pass a ref to function component using forwardRef but never found any explanation WHY we use forwardRef at all.

Here's my codepen to demonstrate my point.

In both cases, clicking the "focus" button next to the input will focus the input to left. The first input utilizes forwardRef while the second doesn't.

Here's the source code for SEO:

import * as React from "https://cdn.skypack.dev/react@17.0.1";
import * as ReactDOM from "https://cdn.skypack.dev/react-dom@17.0.1";

const WithForwardRef = React.forwardRef((props, ref) => {
  return <input type="text" placeholder="WithForwardRef" ref={ref} />;
});

const WithoutForwardRef = ({ myRef }) => {
  return <input type="text" placeholder="WithoutForwardRef" ref={myRef} />;
}

function App() {

  const ref1 = React.useRef();
  const ref2 = React.useRef();

  return (
    <>
      <div>
        <WithForwardRef ref={ref1} />
        <button onClick={() => ref1.current.focus()}>focus</button>
      </div>
      <hr>
      <div>
        <WithoutForwardRef myRef={ref2} />
        <button onClick={() => ref2.current.focus()}>focus</button>
      </div>
    </>
  );
}

ReactDOM.render(<App />, document.getElementById("mainApp"));
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Page not found
  • 2,454
  • 2
  • 10
  • 19
  • 1
    You demonstrated why: `ref` isn't a prop that's passed to your component, it's managed by React. If you want to stick with React's API and offer `ref` for a custom component, `forwardRef` is the way. It helps when you don't have full control over the API, like an HOC. – Emile Bergeron Feb 09 '22 at 18:13
  • 1
    Both comments, your HOC advice and the related question were super helpful for me. Thank you so much! – Page not found Feb 09 '22 at 18:58
  • 1
    Happy it helped! :) – Emile Bergeron Feb 09 '22 at 19:15

0 Answers0