useMemo
is a hook in React that allows you to optimize the performance of your component by memorizing a value that is expensive to calculate. The hook takes two arguments: a function that calculates the value, and a list of dependencies. The memorized value is recalculated only if one of the dependencies has changed.
Here’s a simple example of using useMemo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import React, { useState, useMemo } from 'react'; function Example({ data }) { const [filter, setFilter] = useState(''); // This calculation is expensive, so we only want to do it if the // filter or data has changed. const filteredData = useMemo( () => data.filter(item => item.includes(filter)), [data, filter] ); return ( <div> <input value={filter} onChange={e => setFilter(e.target.value)} /> <ul> {filteredData.map(item => ( <li key={item}>{item}</li> ))} </ul> </div> ); } |
In this example, we have a component that displays a list of items and a filter input. The component uses the useState
hook to keep track of the filter value. The filtered data is calculated using the useMemo
hook and is only recalculated if the data
or filter
has changed.
By using useMemo
, we ensure that the expensive calculation is only performed when necessary, which can help improve the performance of our component.