ref – https://www.w3schools.com/react/react_usememo.asp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
const App = () => { const [count, setCount] = useState(0); const [todos, setTodos] = useState([]); const calculation = expensiveCalculation(count); ... ... const expensiveCalculation = (num) => { console.log("Calculating..."); for (let i = 0; i < 1000000000; i++) { num += 1; } return num; }; |
Use useMemo
To fix this performance issue, we can use the useMemo Hook to memoize the expensiveCalculation function. This will cause the function to only run when needed.
We can wrap the expensive function call with useMemo.
The useMemoHook accepts a second parameter to declare dependencies. The expensive function will only run when its dependencies have changed.
In the following example, the expensive function will only run when count is changed and not when todo’s are added.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
const App = () => { const [count, setCount] = useState(0); const [todos, setTodos] = useState([]); const calculation = useMemo(() => expensiveCalculation(count), [count]); return ( <div> <div> <h2>Expensive Calculation</h2> {calculation} </div> </div> ); }; |