why do we need React forwardRef if we can simple pass the created ref in props? [duplicate]
Asked Answered
Q

1

10

The correct way of passing refs to child components as per react documentation is like this:

import React from 'react';

const Input = React.forwardRef((props, ref) => {
  React.useEffect(() => {
    ref.current.focus();
  }, []);
  return <input type="text" ref={ref} />;
});

export default function App() {
  const inputRef = React.createRef();
  return (
    <div>
      <Input ref={inputRef} />
    </div>
  );
}

But if i try to pass the created ref as a normal prop in any other name then 'ref', this also works as expected.

import React from 'react';

const Input = (props) => {
  React.useEffect(() => {
    props.inputRef.current.focus();
  }, []);
  return <input type="text" ref={props.inputRef} />;
};

export default function App() {
  const inputRef = React.createRef();
  return (
    <div>
      <Input inputRef={inputRef} />
    </div>
  );
}

So the question is, is forwardRef doing something special which we cannot achieve with normal props?

Quartet answered 29/11, 2021 at 5:32 Comment(2)
both your examples are wrong and need to use useRef, search for createRef vs useRef. The rest is explained in the dup answerHedger
The more interesting question is why ref is a reserved word which cannot become a prop unless component is wrapped with awkward forwardRefLiking
F
13

It is not necessary to use forwardRef, as per the official documentation.

Ref forwarding is a technique for automatically passing a ref through a component to one of its children. This is typically not necessary for most components in the application. However, it can be useful for some kinds of components, especially in reusable component libraries. The most common scenarios are described below.

You can do something similar by passing the ref with another prop name like divRef. But if you will pass ref as ref prop, then React will not allow that and will not associate ref with DOM element and will show warning warning

If you want to make your element as natural like other elements and refer them with ref using ref prop keyword, then it is mandatory to forwardRef, otherwise not.

Floodgate answered 29/11, 2021 at 6:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.