TIL: class change forces “Style Recalculation” while style change doesn’t. This could be a major performance optimization in some cases.

Nikoloz Gabisonia
1 min readOct 13, 2021

--

I was bumping my head against the table trying to optimize my web application that took ~260ms to “Recalculate Style” that affected more than 6k html elements.

The reason was simple. I used to trigger css animation by changing parent element’s class attribute directly. In my case using tailwind, from class: “scale-100” to “scale-90”.

Well, turns out this is a pretty bad way to animate things in html, especially those which have thousands of child elements, since changing class(As well as many other things) trigger a reflow/layout and style recalculation.

Solution was simple, instead of modifying classfor animating, change the style attribute instead.

In my case, with React:

From

className = {`${settingsOpen ? “scale-90” : “scale-100”}`}

To

style={{ transform: `${settingsOpen ? “scale(0.9)” : “scale(1)”}` }}

Since transform doesn’t trigger style recalculation either, this whole animation didn’t trigger any layout/reflow or style recalculation for children elements.

Thus, 260ms style recalculation process turned into no style recalculation at all.

Happy coding and keep learning!

--

--