This month we cover:
Performance Optimizations in React 18
This is not the first time we speak about React 18, the out-of-the-box performance improvements it brought and what it was get to know as the new “Concurrent Features”. But did you know how to use those to get the best performance out of your application?
Two of the most interesting Concurrent Features are the new
useDeferredValue() hooks, and this is how they help you optimize performance:
By default, React tries to render after updating all states, i.e., batches the updates and then renders the UI with all changes at once. That’s the desirable behavior most of the time, but when some of those updates take much longer than others, they could totally block UI rendering even if the faster updates are ready.
useTransition(), you can prioritize urgent state updates over the non-urgent ones. That
way, React will know it shouldn’t wait for those slower, non-urgent updates and will render the urgent ones
immediately, rendering again when the slower updates finish. This way, the UI won’t get frozen by the slowest
operations, improving the perceived responsiveness of the application.
This hook does the same job as
useTransition(), but it’s used when we only need the value and
don’t have the state setting function. It tells React that the state update for that value is non-urgent, so
it will defer to more urgent updates. If an urgent render occurs, the component will render with the previous
value and then render again when the actual state update occurs.
Want to know more? In
dev.to they wrote an interesting article with examples and a more in depth explanation of these
features, plus some other optimization tricks with
the good old
Remember that in order to use the new Concurrent Features, you must be on React 18 and use the new Root API.
It’s not a new feature by any means (we had it since ES6), but it’s not always well known, cause it’s not easy to find use cases for it outside library development, and browser support wasn’t great either.
Now that it has widespread browser support, it is a good time to remember how awesome proxies are. If you want to learn more about them, in dev.to they recently wrote a couple of articles:
- Public, private and static class members
- Private member checks with the
- Static initialization blocks
- Top-level await in modules
at()for indexable values (like arrays or strings)
- RegExp match indices
Fortunately, browsers are catching up with standards pretty quickly nowadays and many of these new features already have over 90% of support relative to the global browser share. But anyway, you can start using them today with transpilers like Babel and the core-js polyfills.