Languages
[Edit]
EN

React - useMemo hook example

5 points
Created by:
Dirask Community
6240

In this article, we would like to show how to use useMemo hook in React.

The useMemo hook was created to optimize component logic by not letting to do some operations if it is not necessary.

In below example, we use React.useMemo hook which takes two arguments:

  • an arrow function that returns the value stored in useMemo(),
  • dependency list (in our case [data])

When the component is created, a function from useMemo() is called which returns the result (in our case json). After re-render always the last current useMemo() result is returned. The function from useMemo() will be called again only if there is any dependency change.

Note:

There can be many dependencies, and if even one of them changes the function from useMemo() is called again.

Runnable example:

// ONLINE-RUNNER:browser;

// Uncomment next line during working with JSX Compiler:
// import React from 'react';
// import ReactDOM from 'react-dom';

const App = () => {
	const [counter, setCounter] = React.useState(0);
    const [data, setData] = React.useState(() => ({user: 'john', counter: 0}));
    const json = React.useMemo(() => {
        console.log('Calculation in useMemo when data changed...');
        return JSON.stringify(data, null, 4);
    }, [data]);
    const handleAppClick = () => setCounter(counter + 1);
    const handleMemoClick = () => setData({...data, counter: data.counter + 1});
    console.log('App rendering...');
	return (
      <div>
        <button onClick={handleAppClick}>Increment counter</button>
        <button onClick={handleMemoClick}>Increment data.counter</button>
        <pre>
          {json}
	    </pre>
      </div>
	);
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

ReactJS

React - useMemo hook example
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join