React - useMemo hook example
In this article, we would like to show how to use useMemo
hook in React.
Simple example:
const Json = ({ data }) => {
const json = React.useMemo(() => JSON.stringify(data), [data]); // JSON.stringify() called only when data changed
return (
<pre>{json}</pre>
);
};
// Usage example:
const [data, setData] = React.useState({name: 'John', age: 21}, []);
<Json data={data} />
Where:
json
constant is updated withJSON.stringify()
only whendata
value or references ich changed.
Practical example
The useMemo
hook was created to optimize component logic by not letting to do some operations if it is not necessary.
In the below example, we use React.useMemo
hook which takes two arguments:
- 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 handleCounterUpdateClick = () => setCounter(counter + 1);
const handleDataUpdateClick = () => setData({...data, counter: data.counter + 1});
console.log('App rendering...');
return (
<div>
<button onClick={handleCounterUpdateClick}>Update counter</button>
<button onClick={handleDataUpdateClick}>Update data</button>
<pre>
counter: {counter}
</pre>
<pre>
json:<br />{json}
</pre>
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);