Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

196
Visualizações
Why do we even need forwardRef in React?

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"));
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda