State in useImperativeHandle is not persistent
P粉786800174
P粉786800174 2024-04-01 00:20:12
0
1
302

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粉786800174
P粉786800174

reply all(1)
P粉674999420

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!