It's seems use setState
to animate elements by listening to window.scrollY
would make very choppy effect.
const scrollY = window.scrollY;
animation01: {
transformY: (scrollY > breakPoint01) ? `translateY(200px)` : `translateY(0px)`,
},
I ended up with the solution of ref
to manipulate DOM directly to avoid the choppy effect...
const breakPoint00 = 1250
const breakPoint01 = breakPoint00 + 230
const animation01 = ReactDOM.findDOMNode(this.animation01)
if (scrollY > breakPoint00) {
animation01.style.transform = `translateY(0px)`
} else (scrollY > breakPoint01) {
animation01.style.transform = `translateY(200px)`
}
Why is it so choppy when using the first solution? Is this a right way to do scrolling animation in React?
Generally speaking - Yes, you should use ref
to animate or change style properties with events like scroll, zoom etc. The reason is because when you use setState
you force to rerender component every time you scroll, zoom etc. In addition these events can be called many many times per second, so you can imagine why you get choppy effects.
However, when you change css directly component does not rerender - it only changes style right on the element, so you animation effect is more smoothly.
EDIT
So I decided to create a little demo that illustrates what've been asked in comments under the answer.
Here is jsfiddle little demo
It behaves as you would update component. You can easily check it by inserting console.log('updated')
inside componentDidUdpate
hook - every time you invoke setState
you'll see updated
message. It does not remounts component though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With