useCallback
React’s useCallback hook is another tool for performance optimization. Unlike useMemo which caches the result of a function, useCallback focuses on memorizing the function itself. UseCallback allows you to memorize a function, meaning it returns the same function reference as long as its dependencies haven’t changed. Here’s how it helps.
Syntax:
const memoizedFunction = useCallback(() => {
// Function body
}, [dependencies]);
Example: Below is the code example:
// index.js
import React, { useState, useCallback } from 'react';
function ParentComponent(props) {
const [data, setData] = useState([]);
const handleClick = useCallback(() => {
// Perform action using data
}, [data]);
return (
<div>
<ChildComponent handleClick={handleClick} />
<button onClick={() => setData([...data, Math.random()])}>
Add Item
</button>
{
data.map((val) => (
<li key={val}>{val}</li>
))
}
</div>
);
}
function ChildComponent(props) {
return <button onClick={props.handleClick}>Click me</button>;
}
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>
<ParentComponent />
</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.