This React code snippet utilizes the Context API along with the useMemo hook to optimize performance by sharing data between components efficiently. I...
Back to Snippets
javascript
• 30 lines
JavaScript
JavaScript
JavaScript
React Performance Optimization Using useMemo And useCallback Hooks
This React pattern optimizes performance in functional components by preventing unnecessary re-renders using the useMemo and useCallback hooks. It is particularly useful when dealing with complex computations or expensive function calls, significantly enhancing application performance. The useMemo hook memoizes values, while the useCallback hook memoizes functions, both improving efficiency. By applying this pattern, developers can optimize their React applications for better user experience.
Snippet Stats
Lines
30
Characters
1,222
Read
1 min
/**
* Optimized React component that utilizes useMemo and useCallback for performance enhancement.
*
* @param {object} props - The component props.
* @param {function} props.expensiveFunction - An expensive function to be memoized.
* @param {array} props.dependencyArray - Dependency array for useMemo.
* @return {JSX.Element} The component markup.
*/
import React, { useMemo, useCallback } from 'react';
const OptimizedComponent = ({ expensiveFunction, dependencyArray }) => {
// Memoize the expensive function using useCallback to prevent re-renders.
const memoizedExpensiveFunction = useCallback(expensiveFunction, dependencyArray);
// Memoize a value using useMemo to prevent recalculations.
const memoizedValue = useMemo(() => {
// Simulating an expensive computation.
return Array(1000000).fill(0).map((_, index) => index);
}, dependencyArray);
return (
<div>
<h1>Optimized Component</h1>
<button onClick={memoizedExpensiveFunction}>Trigger Expensive Function</button>
<p>Memoized Value: {memoizedValue.length}</p>
</div>
);
};
export default OptimizedComponent;
Found an issue with this snippet? Help us improve by reporting it. Report it →
Related Snippets
View allThis code snippet demonstrates how to optimize React hooks using useCallback and useMemo to prevent unnecessary re-renders and improve performance. It...
This React hook handles asynchronous data fetching with error handling and loading states, making it useful for fetching data from APIs. It utilizes R...