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

183
Visualizações
React Functional Components change state of parent from child without rendering all children

Changing parent component state from child using hooks in React can be done (as explained in multiple places as here and here) sharing a callback from parent to child:

function Parent() {
    const [value, setValue] = React.useState("");

    function handleChange(newValue) {
      setValue(newValue);
    }

    // Pass a callback to Child
    return <Child value={value} onChange={handleChange} />;
}

And then you can use the callback in Child:

function Child(props) {
    function handleChange(event) {
        props.onChange(event.target.value);
    }
  
    return <input value={props.value} onChange={handleChange} />
}

The downside of that approach is when you have multiple children. The callback must be passed as argument to all children, and because the callback needs access to setValue has to be declared inside the parent function.

So the callback function will be created every time parent is rendered, and it will force to render all children.

I'm using React memo to avoid this issue, so I can define when a child needs to be rendered again, however I'm wondering if there is a better way to solve this issue.

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

This is exactly what useCallback was built for!

useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders

You could modify your parent component to look like:

function Parent() {
    const [value, setValue] = React.useState("");

    const handleChange = React.useCallback((newValue) => {
       setValue(newValue);
    }, []);

    // Pass a callback to Child
    return <Child value={value} onChange={handleChange} />;
}
about 4 years ago · Santiago Gelvez 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