Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

100
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda