onChange calling a parent function: strange behavior; can't read parent state #1713
-
Hi, I am using @react-spring/three. I am trying to call a parent function passed down into a child from useSpring's onChange. The function sets some state variables. The changes go through, but when I try to read the state values I just see their original values. This is not simply a case of not seeing the immediate update because React queues the state changes. The next time the function is called I still see the original value. Here is an example - sorry it has a little more going on but is a lot simpler than my project! The key snippets The useSpring is in Obj.jsx and I call the updateVar - (passed in from the parent), onChange:
The updateVar function in App.js is where I see the odd behavior (which I think probably has something to do with scope?!)
Why can't I read the current state vars from the updateVar function? I am not sure if this is a react-spring issue, or me just not understanding something generic in JS or React, but I posted the question here thinking it might be something other's here have faced. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Because the spring memoizes props. To access the new state in This is similar to calling functions in Here's some helpful docs that might explain it better than I did:
I hope this helps. Here is an updated sandbox demonstrating what I was saying – https://codesandbox.io/s/youthful-star-7qi95?file=/src/Obj.jsx:775-784 |
Beta Was this translation helpful? Give feedback.
Because the spring memoizes props. To access the new state in
app.jsx
the function needs to be updated so you can useuseCallback
and passlastTimeUpdated
as a dependancy. Then inObj.jsx
you passupdateVar
as a dependency to make sure that onChange is calling the most up to date version of the function.This is similar to calling functions in
useEffect
. You normally get a warning about it because it won't be in the deps and if it is in the deps and not wrapped inuseCallback
it'll complain again declaring that whenever the function updates (on every render of the component) the effect will fire.Here's some helpful docs that might explain it better than I did: