onClick with rerender cause useSpring reset
First of all, thank you for this library, it's amazing!
Today i noticed a very strange bug:
if you set an onClick prop that basically update parent state on a stateless component that use useSpring, spring values are resetted.
Try this codesandbox: https://codesandbox.io/s/j7z9k8q68w
Hi @lorenzomigliorero. thanks for pointing this out. good catch actually.
so basically useSpring lets you update the spring values two ways.
- you can overwrite the spring by calling
useSpringwith new values - or you can pass new values the setter function passed back by useSpring
so what is happening here is function Goo() { .... }is updating the spring values with the set function passed back, but whenever onClick is called this makes the function call which calls useSpring again with the initial values, that resets the position of the spring.
for useSpring and other similar hooks, its best to make them fully controlled by state
const [state, setState] = useState(initial)
const [props] = useSpring({...state})
I have modified your fork with one way you my achieve what you are trying to achieve above. codeSanbox
Hi @ruggedy, thanks for your answer. I would have one last question on your codeSandbox:
Why did you create a useRef for the count state on line 12?
Accessing directly to count in the useCallback would have invalidate the memoization?
Thanks in advance, L.
it wouldn't invalidate it, but the memoized callback will only have access to a stale version of count. so in other to get the latest value of ref, it needs to be assigned to a mutable ref. this way the useCallback will always have the latest value of count
Thanks for the explanation!
I noticed some unexpected (to me) behaviour which could be related to this. If you pass a "chain" to useSpring the chain triggers again when the parent rerenders the component, even if the state did not really change. Here's a codesandbox to illustrate this issue (which I made mainly to help myself understand what was going on) I experienced.
https://codesandbox.io/s/usespring-chain-reset-when-parent-updates-pklo0
As you can see, the regular button triggers over and over again when hovered. The memo button does not.
I don't know if this could be prevented somehow or if I am doing something wrong, but I spent quite some time looking into this. Maybe a little heads up in the docs when the chains are mentioned? (Also applies to scripted animations with multiple steps, by the way.)
@robbeman Open a new issue. Thanks! 👍