What is Memoization?
Background
The term “Memoization” came from the Latin word “memorandum” (to remember), which is shortened to “memo” in American English which means “to transform the results of a function into something to remember.”.
Memoization
In computing term, memoization is refered to speed up computer programs by eliminating the repetitive computation of results, and by avoiding repeated method calls that process the same input.
useMemo
In the context of programming, particularly in React.js, `useMemo` is a hook used for memoizing expensive computations so that they are only re-executed when one of the dependencies has changed.
In React, when a component re-renders, all of its code is executed again, including any expensive computations. This can be inefficient if those computations don’t need to be recalculated on every render.
`useMemo` allows you to optimize performance by memoizing the result of a function or computation and only recalculating it when the inputs to that function change. It takes two arguments: the first is a function that performs the computation, and the second is an array of dependencies. The result of the computation is memoized and will only be recalculated when one of the dependencies changes.
Here’s a basic example:
import React, { useMemo } from ‘react’;
const MyComponent = ({ a, b }) => {
const result = useMemo(() => {
// Expensive computation
return a * b;
}, [a, b]); // Recalculate result only if ‘a’ or ‘b’ changes
return <div>{result}</div>;
};
export default MyComponent;
In this example, the multiplication of `a` and `b` is an expensive computation. By using `useMemo`, we ensure that the multiplication is only performed again if either `a` or `b` changes. This can lead to significant performance improvements in components with complex computations.
React’s functional component uses the useMemo hook, which yields a memoized value.
Syntex
useMemo() is a built-in React hook that accepts two arguments — a function compute that computes a result, and the depedencies array
react.memo
react.memo is used in higher-order component that is used to memoize a component, which means it caches the output of the component and only re-renders it if its props have changed. This can be useful when a component’s rendering is expensive, and you want to avoid unnecessary re-renders. Memo can be imported from ‘react’ and wrapped around a functional component.
useMemo vs useCallback
The useMemo and useCallback Hooks are similar. The main difference is that useMemo returns a memoized value and useCallback returns a memoized function
What problem solved in useMemo ?
Improve Application Performance
How to implement Memoization concept in class component ?
Using PureComponent
Does useMemo have any disadvantage?
Yes we can’t call useMemo in loop like
Resolution
YouTube Video
For Other Awsome Article visit AKCODING.COM
Read Article in Medium