useMemo in React with sample
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,… ادامه »useMemo in React with sample