useMemo hooks in React Js
- Get link
- X
- Other Apps
useMemo hooks in React Js
useMemo
is a React hook that is used to optimize the performance of a React component by memoizing the result of a function.
When a component is re-rendered, React may execute expensive calculations or functions, even if their input values have not changed. This can be inefficient, especially for large or complex components. useMemo
allows you to memoize the result of a function so that it is only re-computed when its input values change.
The useMemo
hook takes two arguments:
- A function that returns the memoized value.
- An array of dependencies that determine when the memoized value should be re-computed.
Here is an example of how to use useMemo
:
import React, { useMemo } from 'react'; function MyComponent(props) { const memoizedValue = useMemo(() => { // Expensive calculation return props.someProp * 2; }, [props.someProp]); return <div>{memoizedValue}</div>; }
In this example, useMemo
is used to memoize the result of the expensive calculation, which is the multiplication of props.someProp
by 2. The array [props.someProp]
is the dependency array, which specifies that the memoized value should be re-computed whenever props.someProp
changes.
By using useMemo
, the expensive calculation is only executed when props.someProp
changes, and not on every re-render of the component. This can significantly improve the performance of the component.
Real Time Example of useMemo:
Suppose we have a component that displays a list of products, and we want to filter the products by category. We have a function filterProducts
that takes a list of products and a category, and returns a filtered list of products that match the category:
function filterProducts(products, category) { return products.filter(product => product.category === category); }
ProductList
component that takes a list of products and a category as props, and displays the filtered list of products:In this example, we use useMemo
to memoize the result of the filterProducts
function. The filteredProducts
variable is only re-computed when props.products
or props.category
changes.
This means that if the user selects a new category, the filteredProducts
variable will only be re-computed with the new category value, instead of re-computing the filtered list of products for every re-render of the component.
This can significantly improve the performance of the ProductList
component, especially if the list of products is large or the filtering function is expensive.
Happy Learning!! Happy Coding!!
- Get link
- X
- Other Apps
Comments