useMemo

📚 Table of Contents

Introduction

useMemo is a React Hook that lets you "cache" the result of a calculation between the re-renders.

const cachedValue = useMemo(funcForCalculation, dependencies)

Example

import React, { useMemo } from 'react'; const calculateValue = (val) => { let total = 0; for (let i = 0; i < 1e7; i++) { total += val; } return total; } const ExpensiveComponent = ({ val }) => { const result = useMemo(() => { return calculateValue(val) }, [val]); return <div>Result: ${ result }</div> }
const App = () => { return <ExpensiveComponent val={10}> }

Memo

In react by default if a component re-renders it will recursively re-renders it's child componenets as well. If the number of children components are less, it won't show much effect. But if you experienced the slowness while re-rendering the children and you know that the props passed to the child components won't change, then actual you can cache that children component as well by wrapping the component around memo().

Example-1

Before Memoization (Inefficient Re-render)

import React, { useState } from 'react'; function ChildComponent({ name }) { console.log('Child rendered'); return <div>Child Component - Name: {name}</div>; } function ParentComponent() { const [count, setCount] = useState(0); return ( <div> <h2>Count: {count}</h2> <button onClick={() => setCount(count + 1)}>Increment</button> <ChildComponent name="Siva" /> </div> ); } export default ParentComponent;

After Memoization (Efficient Re-render)

import React, { useState, memo } from 'react'; const ChildComponent = memo(function ChildComponent({ name }) { console.log('Child rendered'); return <div>Child Component - Name: {name}</div>; }); function ParentComponent() { const [count, setCount] = useState(0); return ( <div> <h2>Count: {count}</h2> <button onClick={() => setCount(count + 1)}>Increment</button> <ChildComponent name="Siva" /> </div> ); } export default ParentComponent;

Use Cases

Add these in Use Cases for more practical appeal: