
What is React's useMemo
Requirements
- React.js (16.8 or newer)
Introduction
React's , much like memo and useCallback, is used to optimize the rendering of given React function component by memoizing it. Although every one of them have different use cases.
Problem
Let's say you have this component:
import React, { useState } from "react"; const array = [1, 2, 4, 5, 8]; export default function App() { const [localState, setLocalState] = useState(0); function sum() { return array.reduce((acc, curr) => acc + curr); } return ( <div> <p>Local State: {localState}</p> <button onClick={() => setLocalState(localState + 1)}> Change Local State </button> <h1>{sum()}</h1> </div> ); }
The example above shows a scenario that works but as you might suspect, not efficiently. The function will always return the same result, but it will be recreated at every button click, as the button is updating state, and every state update the component re-renders. Every time
is recreated, it will run again in the jsx.
Solution
To avoid the function to be recreated we'll use as such:
import React, { useState, useMemo } from "react"; const array = [1, 2, 4, 5, 8]; export default function App() { const [localState, setLocalState] = useState(0); function sum() { return array.reduce((acc, curr) => acc + curr); } const memoizedSumValue = useMemo(sum, []); return ( <div> <p>Local State: {localState}</p> <button onClick={() => setLocalState(localState + 1)}> Change Local State </button> <h1>{memoizedSumValue}</h1> </div> ); }
The hook will execute the function passed as first argument and memoize its return value, if the value doesn't change, the function will not be recreated and re-executed.
TLDR
basically execute the function passed at the first argument and memoize the return
Additional Resources
Related Posts
- What is React's useCallback?2021-09-02
- What does the useReducer hook do2023-01-05
- How to use Debounce in Reactjs?2023-01-04
- What is React's useMemo2021-09-02
- What is React's Context API?2021-08-28
- React - What is Prop Drilling?2021-08-28
- React - Controlled Vs Uncontrolled2021-08-27