JS is very nice when
- Mobile and desktop UI are very different
- Easier to have 2 distinct HTML structure (cards vs table, burger menu vs horizontal menu) instead of having one and use media queries
- To display/hide things
JS allows for:
- Minimal DOM
- Easy to test: "should display the details when I click on the button" vs difficult to unit test CSS
- The less you have in the DOM, the less you ask React to compute it
CSS has a huge advantage: it's instantaneous
but each time you have a user interaction (click on a button) in front of it, this advantage is gone
--
Real-life example: a burger menu (mobile) with a lots of entries (level 1, level 2, level 3)
When clicking on a menu entry, the app was slow to display the submenu (~800ms)
The first implementation used "display: none" to hide entries outside the current level.
Solution:
- Do not ask React to compute things not displayed to the user (like in video games: don't compute what is not displayed)
Use JS if/else, ternary, &&... instead of CSS "display: none" ("opacity: 0", HTML hidden attribute and others) - One DOM for the burger menu and a dedicated DOM (hidden) for SEO
Results:
- INP (Interaction to Next Paint) down from ~800 to 96ms
- Burger menu DOM down from 3800 to 63 elements