Alright what is Memoization first?
In computing, memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.
In other words, Memoization is a way to lower a function's time cost in exchange for space cost; that is, memoized functions become optimized for speed in exchange for a higher use of computer memory space.
If you see the diagram below, a function named sum is getting called multiple times. Even though the function is called with the same parameters 1,2
it has to re-calculate the result.
Well, wouldn't it be nice if we put the already calculated result and store somewhere in memory against the parameters passed while each call. This way we can return directly from the memory if we observe that the result for the passed parameter was already calculated?
Have a look at below function call diagram, you can see that the result is directly being return from memory when we are calling memoSum(1,2)
for the second time with same parameters 1,2
.
This is pretty much fine to have a function without memoization if we are considering a function which is not CPU intensive, but however, if you consider a pure function which is very frequently called, and takes considerable amount of time to return the results, it's better to memoize the function, so that already computed results can be used instead of computing again and again for the same parameters.
Always remember that only pure functions can be memoized. If you don't have a clue about what makes a function pure, you might want to follow the following article written by ysael pepin
which explains on of the most basic concepts of functional programming - https://dev.to/ysael/functional-programming-basics-part-1-pure-function-e55
How can we memoize a given pure function?
Well there are bunch of libraries available which has already implemented memoization and made it available different API's for that.
Lodash is one of the JavaScript libraries that provides memoize
function to solve this problem.
But what memoization has to do with React components?
As we already know that a React component is just like another JavaScript function that returns bunch of HTML tags, that we call JSX and the parameters passed to this very function is called Props
.
Yes your guess is right, we can definitely memoize a React component.
Memoizing a React Component with React.memo
const MemoizedComponent = React.memo(function MyComponent(props) {
/* render using props */
});
React.memo is a higher order component. Itβs similar to what React.PureComponent does, but for functional components.
If your function component renders the same result given the same props, you can wrap it in a call to React.memo()
for a speedy rendering in some cases by memoizing the result. This means that React will skip rendering process for the component and doesn't perform a virtual DOM difference check, it will just re-use the last rendered result.
export function PassengerDetails({ passengerName, departureDate }) {
return (
<div>
<div>Passenger: {passengerName}</div>
<div>Departure: {departureDate}</div>
</div>
);
}
export const MemoPassengerDetails = React.memo(PassengerDetails);
By default it will only shallowly compare complex objects in the props object.
If you want control over the comparison, you can also provide a custom comparison function as the second argument.
export function PassengerDetails({ passengerName, departureDate }) {
return (
<div>
<div>Passenger: {passengerName}</div>
<div>Departure: {departureDate}</div>
</div>
);
}
function areEqual(prevProps, nextProps) {
/*
return true if passing nextProps to render would return
the same result as passing prevProps to render,
otherwise return false
*/
}
export default React.memo(PassengerDetails, areEqual);
Limitations
- To be able to memoize, the function must be a pure function.
- Where space is critical than computation time, you might not need to memoize you function.
- When you function is less frequently executed, there's no much benefit of memoizing the function.
Things to remember
- Instead of Lodash's
memoize
use React.memo to memoize React components as the later one is more optimized to work with React components. - React.memo only compare props shallowly, if you want to deep compare the props then it's better to pass your own compare function as a second parameter in
React.memo
function. - Do not get confused
React.memo
withuseMemo
, you can learn aboutuseMemo
which is explained well byLinas Spukas
in the following article - https://dev.to/spukas/react-usememo-for-optimisation-5gna
If you find the article informative, please don't forget to follow.
Happy coding :)
Interested in having a look at my other articles?
Learn some of the best practices in web accessibility that will help your web content or web application reach out to a broader audience.
Learn how code splitting is a thing that you have been missing.
Route-based code splitting in ReactJS
Raushan Sharma γ» Dec 8 '19
Find out how Optional chaining and Nullish coalescing can make your code look more clean and readable.
Top comments (3)
Let's remind react to remember components
Awesome!
nice post
thanks man