I thought react-spring (useSpring) causes the component to re-render, but it may not? #1436
-
🤓 QuestionI guess the main question is, how do we know what situation will react-spring re-render a lot and how to we prevent it if possible? I thought react-spring However, I can see that it re-renders a lot, in: https://codesandbox.io/s/musing-dew-9tfi9?file=/src/App.tsx (by looking at the console.log output, which has a lot of print out of Likewise, if it is a component that is similar to react-spring, it'd render a lot: https://codesandbox.io/s/wonderful-currying-9pheq However, the following code: let renderCount = 0
export default function App() {
const styles = useSpring({
loop: true,
to: [
{ opacity: 1, color: '#ffaaee' },
{ opacity: 0.5, color: 'rgb(14,26,19)' },
{ transform: 'translateX(100px)' },
{ transform: 'translateX(0px)' },
],
from: { opacity: 0, color: 'red', transform: 'translateX(0px)' },
config: { duration: 500 },
})
console.log('renderCount', ++renderCount)
return <a.div style={styles}>I will fade in and out</a.div>
} Demo: https://codesandbox.io/s/dazzling-rgb-j2bx3?file=/src/App.tsx We can see that the How and why doesn't react-spring cause a lot of re-rendering in this case, and how do we know in what situation would react-spring cause a lot of re-rendering (and how to prevent it)? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 7 replies
-
The API allows spring to animate outside of the react-render loop. In the first example you shared, you're using state to dictate the props of the spring. In the third example you've shared you've got your spring defined and ready so the You could also look at using the Imperative API we now have which would allow you to change the state of the spring in reaction to events without updating the state of the component. So that's the kind of how and why but in summary: HOW – the animated component How to prevent it? IMO use the imperative api, i linked above, this is how I write all my springs and I haven't had any issues so far. |
Beta Was this translation helpful? Give feedback.
-
so I kind of get it... when you say imperative vs declarative... when it is done like https://codesandbox.io/s/wonderful-currying-9pheq (the shaking text) |
Beta Was this translation helpful? Give feedback.
The API allows spring to animate outside of the react-render loop. In the first example you shared, you're using state to dictate the props of the spring. In the third example you've shared you've got your spring defined and ready so the
animated
component does not need to have a re-render to have it's styles updated.You could also look at using the Imperative API we now have which would allow you to change the state of the spring in reaction to events without updating the state of the component. So that's the kind of how and why but in summary:
HOW – the animated component
WHY – it's better and more performance efficient to be honest.
How to prevent it? IMO use the imperative api, i lin…