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

114
Visualizações
React, should a hook result be passed down from parent to child component?

Very often when using a hook on a parent component one of its children will also need to use it. Is it better (performance / readability wise) to pass a function that we get from a hook down to a child component or to get it from scratch?

Here's a demo of what I mean:

import { useTranslation } from "react-i18next";

// Parent component
export default function App() {
  const { t: formatMessage } = useTranslation();

  return (
    <div className="App">
      <p>{formatMessage("Welcome to React")}</p>
      <MyButton1 text="Click me!" formatMessage={formatMessage} />
      <MyButton2 text="Click me!" />
    </div>
  );
}

// Option 1: pass formatMessage as a prop
const MyButton1 = ({ text, formatMessage }) => {
  return <button>{formatMessage(text)}</button>;
};

// Option 2: create a new instance of useTranslation
const MyButton2 = ({ text }) => {
  const { t: formatMessage } = useTranslation();

  return <button>{formatMessage(text)}</button>;
};

Both components work, but <MyButton1 /> gets the formatMessage function directly from his parent, and <MyButton2 /> creates a new instance. I've seen code bases that use both options. Which one do you think is the best one?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

First case:

If a Child component is a direct child of a Parent component that has called the hook, and Child will always receive the needed prop everywhere it is used, I think it is better to use the first option, as it will result to less function calls. It depends on what the hook does, but it may save some CPU.

Second case:

If Child is deep nested, the second option is great as otherwise it will result to what known as Prop Drilling. Also, if you want Child to be completely independent from its parent, you would wanna go with the second option.

about 4 years ago · Juan Pablo Isaza Relatório
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