How to use React useMemo Hook
In this post we will see how to use the React useMemo() Hook
What is useMemo()
useMemo is similar to useEffect, the only difference is that useEffect renders a function everytime a component renders, but useMemo renders only during the component's first render and it will cache the value and recomputes only if the state changes.
Example without useMemo()
import React, { useState} from "react";
function App() {
const [data, setData] = useState("react");
const lengthData = () => {
return data.length;
}
return (
<div>
<h1>{lengthData()}</h1>
<h1>{lengthData()}</h1>
<h1>{lengthData()}</h1>
</div>
);
}
export default App;
In the above code lengthData() function is called 3 times, so the same function will run for 3 times.
Example with useMemo()
import React, { useState} from "react";
function App() {
const [data, setData] = useState("react");
const lengthData = useMemo(() => {
return data.length;
}, [data]);
return (
<div>
<h1>{lengthData}</h1>
<h1>{lengthData}</h1>
<h1>{lengthData}</h1>
</div>
);
}
export default App;
In the above code lengthData() function is inside useMemo hook, so it will be called only once during render and the result will be cached and the function will be recomputed only when the data is changed.