Ways to handle errors in React:
🔹 1. Using Error Boundaries (for class components only)
Error boundaries catch JavaScript errors anywhere in the child component tree and display a fallback UI.
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error("Error caught:", error, info);
}
render() {
if (this.state.hasError) {
return <h2>Something went wrong.</h2>;
}
return this.props.children;
}
}
// Usage
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>
🔹 2. Try-Catch for Event Handlers & Sync Code
function handleClick() {
try {
// risky operation
} catch (error) {
console.error("Error:", error);
}
}
🔹 3. Handling Errors in Async Code (e.g., fetch/axios)
useEffect(() => {
async function fetchData() {
try {
const res = await fetch('/api/data');
const json = await res.json();
} catch (err) {
console.error("Fetch error:", err);
}
}
fetchData();
}, []);
🔹 4. Optional Chaining + Fallbacks (To avoid undefined/null errors)
const name = user?.profile?.name || 'Guest';
🔹 5. React Query / SWR Error Handling
If you're using tools like React Query, it provides built-in error states:
const { data, error, isError } = useQuery('user', fetchUser);
if (isError) return <div>Error: {error.message}</div>;
✅ Summary:
- Use Error Boundaries for unexpected UI crashes.
- Use try-catch in sync & async logic.
- Use optional chaining for safer access.
- Use tool-specific error handling in libraries like React Query.