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?
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 withuseEffect
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