0
votes

I have a state variable which holds components created dynamically, however, when I access the state from a function passed to the child as props, I get the state status from back when it was created. Not so when I log useEffect.

For example: I add 3 children, and in the function logMyChildren I get the state previous to the creation of the last Child element.

First Child mychildren is []

Second Child myChildren is [{Child with id 0}]

Third Child myChildren is [{Child with id 0}, {Child with id 1}]

It gives me the same state with each Child every time I call that function.

Is there a way to get the current state(not a state from the past) regardless of the children?

const Parent = () => {
  const [myChildren, setMyChildren] = useState([])

  const addChild = () => {
    let id = myChildren.length + 1
    setMyChildren([
      ...myChildren,
      <Child key={id} id={id} logMyChildren={logMyChildren} />,
    ])
  }

  const logMyChildren = (id) => {
    console.log(id, myChildren)
  }

  useEffect(() => {
    console.log(myChildren)
  }, [myChildren])

  return (
    <>
      <button onClick={addChild}>Add a child</button>
      {myChildren && myChildren.map((child) => child)}
    </>
  )
}

const Child = ({ id, logMyChildren }) => {
  return (
    <>
      <p>A child with id {id}!</p>
      <button onClick={() => logMyChildren(id)}>X</button>
    </>
  )
}

Every time useEffect() runs, it has the updated state. Thanks.

1

1 Answers

1
votes

The problem for you is that you are creating logMyChildren that encloses state variable (in your case mychildren). What you could do is to use useRef

Something like this:

const stateRef = useRef();
stateRef.current = myChildren;

And then in logMyChildren you use ref - stateRef:

console.log(id,stateRef.current);