You probably know saying "Premature optimization is the root of all evil", but is all optimization premature and evil?
Sometimes 1% differences can have a significant impact.
In a world where everybody is using their phone for browsing the internet, small optimizations can mean additional minutes of browsing time on a single charge.
Today I wanted to write about a little feature in React that will help you on your journey of 1% improvements.
useMemo()
is a hook that returns the memoized value. We can use this hook when we want to avoid calculations every time we render the component. The first argument of the useMemo()
hook is a function we create, and the second is an array of dependencies. By passing a function to useMemo()
hook, it will be called in the first render, and the stored value will be returned on each subsequent re-render, so you can avoid additional calculations each time the component is rendered. However, if one of the values passed in the array of dependencies changes, the function will be called again to obtain and store the new value.
It's important to first write code that works and then add performance optimization to it using useMemo()
. Properly used useMemo()
does not change anything in the behavior of the application, it only affects performance.
The examples of useMemo()
based on a counter are everywhere, so I'm adding my simple example below.
I'm creating a quiz in which content will be defined by the user, the quiz will have multiple stages/steps. Depending on the stages of the quiz, as well as the selected language, I want to display a different label on the button. For example, when displaying questions, the footer with "prev" / "next" buttons will be displayed, but when it is the last question, instead of "next" I will display "submit" on the button, etc.
This way the label won't be recalculated until we move to another 'stage' of the quiz. Otherwise, a re-render is not needed. It may be a small change, but it things like that add up.
I think it's always a good idea to review your code and consider if there's any room for improvement.
Top comments (0)