×
☰ See All Chapters

React useMemo Hook

In this tutprial, you’ll store the results of slow data calculations with the useMemo Hook. You’ll then incorporate the useMemo Hook in an existing component and set conditions for data re-calculations. By the end of this tutorial, you’ll be able to cache expensive functions so that they will only run when specific pieces of data change.

React provides a special Hook called useMemo that you can use to preserve parts of your component across re-renders. The Hook takes two arguments. The first argument is a function that will return the value you want to memoize. The second argument is an array of dependencies. If a dependency changes, useMemo will re-run the function and return a value.

useMemo(compute, dependencies)

In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.

During initial rendering, useMemo(compute, dependencies) invokes compute, memoizes the calculation result, and returns it to the component. If during next renderings the dependencies don't change, then useMemo() doesn't invoke compute but returns the memoized value. But if dependencies change during re-rendering, then useMemo() invokes compute, memoizes the new value, and returns it.

demo.component.js

import { useState } from 'react';

 

export function DemoComponent() {

        const [number, setNumber] = useState(1);

        const [inc, setInc] = useState(0);

        const factorial = factorialOf(number);

        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}

                        &nbsp; &nbsp; <button onClick={onClick}>Re-render</button>

                </div>

        );

}

function factorialOf(n) {

        console.log('factorialOf(n) called!');

        return n <= 0 ? 1 : n * factorialOf(n - 1);

}

export default DemoComponent;

index.js

import React from 'react';

import ReactDOM from 'react-dom';

import './index.css';

import DemoComponent from './components/demo.component';

import reportWebVitals from './reportWebVitals';

 

ReactDOM.render(

  <React.StrictMode>

    <DemoComponent></DemoComponent>

  </React.StrictMode>,

  document.getElementById('root')

);

 

reportWebVitals();

 

react-usememo-hook-0
 
react-usememo-hook-1
 

All Chapters
Author