Home  >  Q&A  >  body text

State in useImperativeHandle is not persistent

Suppose I am in this state:

const [data, setData] = useState([]);

and put it in useImperativeHandle like this:

useImperativeHandle(ref, () => ({
   data,
}));

When I use useEffect to track if the state changes like this:

useEffect(() => {
   console.log(componentRef.current.data);
}, [componentRef.current.data])

It doesn't work, only if I check it manually, like there is a button onClick it will print it, otherwise it is not stateful. Why is this happening? Is there any other way to make it work? Or is it the only way to transfer state to parent?

P粉786800174P粉786800174173 days ago264

reply all(1)I'll reply

  • P粉674999420

    P粉6749994202024-04-01 18:22:37

    useEffect is not reactive. It doesn't track things. It just compares the dependencies between renders and if there are differences, it executes the given callback. Components with useEffect should re-render to perform the function.

    What you can do is pass a callback from the parent to the child so that the child can call it when it changes state

    reply
    0
  • Cancelreply