This React pattern optimizes performance in functional components by preventing unnecessary re-renders using the useMemo and useCallback hooks. It is ...
Back to Snippets
javascript
• 44 lines
JavaScript
JavaScript
JavaScript
Optimizing React Components With Memoization And Error Handling
This React code snippet utilizes memoization to enhance performance by minimizing unnecessary re-renders, particularly useful in scenarios involving complex computations or API calls. It also demonstrates proper error handling techniques, ensuring robustness in component functionality. The snippet is built using functional components and hooks, adhering to industry-standard patterns. By leveraging memoization and error handling, developers can significantly improve the efficiency and reliability of their React applications.
Snippet Stats
Lines
44
Characters
1,491
Read
2 mins
/**
* React component that demonstrates memoization and error handling.
*
* @param {object} props - Component properties
* @param {function} props.onFetchData - Function to fetch data
* @returns {JSX.Element} The rendered component
* @throws {Error} If data fetching fails
*/
import React, { useState, useEffect, useMemo, useCallback } from 'react';
const MyComponent = ({ onFetchData }) => {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
// Memoize the fetch data function to prevent re-renders
const fetchData = useCallback(async () => {
try {
const result = await onFetchData();
setData(result);
} catch (error) {
setError(error.message);
}
}, [onFetchData]);
// Use effect to fetch data on mount
useEffect(() => {
fetchData();
}, [fetchData]);
// Memoize the rendered content to prevent unnecessary re-renders
const content = useMemo(() => {
if (error) {
return <div>Error: {error}</div>;
} else if (data) {
return <div>Data: {JSON.stringify(data)}</div>;
} else {
return <div>Loading...</div>;
}
}, [data, error]);
return content;
};
export default MyComponent;
Found an issue with this snippet? Help us improve by reporting it. Report it →
Related Snippets
View allThis React code snippet utilizes the Context API along with the useMemo hook to optimize performance by sharing data between components efficiently. I...
This code snippet demonstrates how to optimize React hooks using useCallback and useMemo to prevent unnecessary re-renders and improve performance. It...