Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!