preact icon indicating copy to clipboard operation
preact copied to clipboard

Optimized styles calculations 🧮

Open sanjaiyan-dev opened this issue 3 years ago • 3 comments

Adding requestAnimationFrame as pollyfill for useInsertionEffect, for optimized styles related calculations by synchronizing to the refresh rate of the screen, resulting in the most high-fidelity animations possible 🧮

Benefits-:

  • The browser can optimize it, so animations will be smoother.
  • Animations in inactive tabs will stop, allowing the CPU to chill.
  • More battery-friendly.

For more ref-:

  1. https://web.dev/optimize-javascript-execution/#use-requestanimationframe-for-visual-changes
  2. https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

sanjaiyan-dev avatar Nov 05 '22 07:11 sanjaiyan-dev

Hmm, this adds another delay though while it normally seems to run earlier than a layout-effect. This will align the callback more with the timing of useEffect as that is flushed after commit in an animationFrame

JoviDeCroock avatar Nov 05 '22 08:11 JoviDeCroock

Yeah, I'm not sure I understand the motivation here. AFAIK useInsertionEffect is typically called once, and often invalidates styles asynchronously (by inserting a stylesheet or similar).

developit avatar Nov 08 '22 14:11 developit

Hi (@developit & @JoviDeCroock )

I thought this would improve the performance by running useInsertionEffect inside requestAnimationFrame which executes code on the next available screen repaint, which syncs with browser & hardware. It makes smoother animation.

Where useInsertionEffect effect commits before Virtual DOM is committed to the "real" DOM, thus preventing the "flash of the screen".

Extremely sorry for the inconvenience :(

sanjaiyan-dev avatar Nov 08 '22 16:11 sanjaiyan-dev

Going to close this on out, as Jovi and Jason mentioned, this seems like the wrong implementation. Per react.dev, the point of this API is to fire pretty early:

useInsertionEffect allows inserting elements into the DOM before any layout Effects fire.

Adding extra delay seems incorrect to me too.

rschristian avatar Apr 23 '24 07:04 rschristian