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

103
Visualizações
How to pass parent's latest state to child components that are elements of the state in React

Here, I meant parent and child to be App() and Child() respectively in the code below.

App() has a state, myState, which is an array of Child().
Each Child() is basically a <button> with a certain property which holds myState, and prints id of each Child() in myState to console when pressed.

What I expect is that when Child() is pressed, the latest myState is printed.
However, the myState acctually printed looks like the version of when it was passed, and not the latest.

Is there any solution to make the myState property passed to Child() point the latest myState?

Having added several children, you can check the myState of each Child() at the console by pressing them.
For example, pressing ADD button twice makes 2 additional buttons appear.
When the Child() initially added (id of 'initial') is pressed, it properly prints the ids, 1 and 2.
However, when ID: 1 is pressed, nothing prints, and when ID: 2, only 1.

import React, { useState } from 'react';
import './App.css';

function App() {
  const [myState, setMyState] = useState([] as JSX.Element[]);

  /* 
    Below is a BAD state-passing example.
    setMyState makes myState point to an new array with another Child appended,
    although myState passed to the new Child references to the old array.
    Is there any way to pass the latest myState to Child???
  */
  function add() {
    setMyState([...myState, <Child key={myState.length + 1} id={myState.length + 1} myState={myState} />]);
  }

  return (
    <div className="App">
      <button onClick={add}>ADD</button>
      <Child key="initial" id="initial" myState={myState} />
      {myState}
    </div>
  );
}

function Child({ id, myState }: any): JSX.Element {
  return (
    <div>
      <button id={id} onClick={() => {
        for (let child of myState as JSX.Element[]) {
          console.log(child.props.id);
        }
        }}>ID: {id}</button>
    </div>
  );
}

export default App;


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