UseMemo
The useMemo hook in React.js allows you to memorize the result of a function, meaning it caches the output and only re-evaluates the function when its dependencies change. This can improve performance by avoiding unnecessary computations on every render.
Syntax :
const memoizedValue = useMemo(() => {
// Expensive computation or function here
return result;
}, [dependencies]);
Example: Below is the code example:
// index.js
import React, { useMemo } from 'react';
import ReactDOM from 'react-dom/client';
import './style.css'
function UseMemo() {
const [count, setCount] = React.useState(0);
// Simulate an expensive function to generate items
const generateItems = useMemo(() => {
const newItems = [];
for (let i = 0; i < count * 5; i++) {
newItems.push(`Item ${i + 1}`);
}
return newItems;
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(prev => prev + 1)}>
Increment
</button>
<ul>
{generateItems.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<div id='main_container'>
<div>
<img src=
'https://media.w3wiki.org/gfg-gg-logo.svg' alt='gfg_logo' />
</div>
<UseMemo />
</div>
);
Output:
Mastering Performance Optimization Techniques with React Hooks
In this article, we will explore advanced performance optimization techniques using React Hooks. We’ll delve into memoization, callback optimization, preventing unnecessary renders, state updates, and more. By mastering these techniques, developers can significantly enhance the performance of their React applications.