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

276
Visualizações
How to refresh data of parent in child component using function components in React?

I have trouble with updating data of a parent component inside of a child component. I'm using React 18.2.0 with functional components.

To provide a basic code example for my problem:

Parent.js

export default function Parent() {
    const [counter, setCounter] = useState(0);
    const [stuff, setStuff] = useState([]);
    const [items, setItems] = useState("");
    const [size, setSize] = useState(2);

    useEffect(() => {
        refresh();
    }, [size]);

    function refresh() {
        let newStuff = Array(size).fill().map((_, index) => {
            return <Child key={index} counter={counter} items={items} setItems={setItems}/>;
        });

        setStuff(newStuff);
    }
}
...

Child.js

export default function Child({counter, items, setItems}) {
    useEffect(() => {
        refresh();
    }, [counter]);

    function refresh() {
        setItems(items + "test");
    }
}

So to explain it in a basic way: I have parent who has a counter, a string and an array as useState. The array "stuff" has many child components in one layer, the string "items" is here to be edited from the different child components.

The plan is to manually (e.g. through a button click) increment "counter", so that the useEffect in all child components fires and thus items should be edited.

But the problem is that the useEffect in the child component does not register that "counter" is incremented even though it is a useState variable.

So how can I go about this? I have one parent component which has a dataset which is modified by many child components in which lie in the parent component.

What am I missing? Do I have to use some other react functionalities (e.g. useRef, useContext or something)?

about 4 years ago · Santiago Trujillo
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