React useMemo: How to Cache the Value of Expensive Utilities?
To use `useMemo`, we provide it with a function and an array of dependencies. The function is called during rendering, and its return value is cached until one of the dependencies changes.
Syntax of useMemo Hook:
const memoizedValue = useMemo(() => {
// Expensive computation
}, [dependency1, dependency2, ...]);
Example: In this example we will see an optimizing expensive utility functions with React useMemo Hook.
Javascript
import React, { useState, useMemo, useEffect } from 'react' ; const Memoized = () => { const [count, setCount] = useState(0); // Memoized function using useMemo const expensiveOperation = useMemo(() => { console.log( 'Creating expensive operation...' ); return () => { console.log( 'Performing expensive operation...' ); let result = 0; for (let i = 0; i < 1000000000; i++) { result += i; } console.log( 'Expensive operation... Done' ); return result; }; }, []); /* Dependency array - empty array indicates no dependencies */ // useEffect to log when the component is rendered useEffect(() => { console.log( 'Component is rendered' ); }); /* useEffect to simulate component mount and execute expensive operation */ useEffect(() => { console.log( 'Executing expensive operation...' ); const result = expensiveOperation(); console.log( 'Expensive operation result:' , result); }, [expensiveOperation]); return ( <div> <button onClick={() => setCount(count + 1)}> Increment Count </button> <p>Count: {count}</p> </div> ); }; export default Memoized; |
Output:
Explanation of Output:
- We create a component called Memoized that keeps track of a count using useState.
- We use useMemo to remember the result of a big math calculation. This calculation happens only once due to empty dependency array.
- useEffect is used to trigger expensiveOperation for the calculation inside it.
- Now, whenever the component re-renders, the calculation is only done again if the expensiveOperation function changes.
How to use useMemo Hook in a Functional Component in React ?
In React development, optimizing performance is crucial for delivering responsive and fast user experiences. One way to achieve this is by using the `useMemo` hook.
In this article, we’ll explore what `useMemo` is, why it’s beneficial, and how to use it effectively in functional components.
Table of Content
- What is React useMemo?
- Why do we use useMemo?
- React useMemo: How to Cache the Value of Expensive Utilities
- Conclusion: