Day 16 of 50 Days of React: useMemo Hook in React.

Aman Khan
2 min readAug 1, 2022

--

What is useMemo Hook in React?

A. The React useMemo Hook returns a Memoized value😁.

Think of Memoization as caching a value so that it does not need to be recalculated.

The useMemo only runs when one of its dependencies updated🙄.

If during next renderings the dependencies don’t change, then useMemo doesn't invoke itself but returns the memoized value.

This improves performance.

The useMemo and useCallback Hooks are similar. The main difference is that useMemo returns a memoized value and useCallback returns a memoized function.

Why we need it?

The useMemo Hook is used to keep resource intensive functions from needlessly running and use the already calcaluted values.

UseCase📝

A component <CalculateFactorial /> calculates the factorial of a number.

import { useState, useMemo } from 'react';export function CalculateFactorial() {const [number, setNumber] = useState(1);const [inc, setInc] = useState(0);
const factorial = useMemo(() => factorialOf(number), [number]);
# Whenever a number comes up it will be memoized and if the number already exist than it will be returned by useMemo.
const onChange = event => {setNumber(Number(event.target.value));};const onClick = () => setInc(i => i + 1);return (<div>Factorial of<input type="number" value={number} onChange={onChange} />is {factorial}<button onClick={onClick}>Re-render</button></div>);}function factorialOf(n) {console.log('factorialOf(n) called!');return n <= 0 ? 1 : n * factorialOf(n - 1);}

In the next article I will be writing about Custom Hooks🤔 ?

That’s all for Today, Stay Tuned and I will see you in the next one👋🏻.

Link to Day 17

Thanks for Following and Claps😋

--

--

Aman Khan

Blockchain and Web3 Engineer Crafting compelling stories at the intersection of tech, business, and culture.