Category: react
error handling in react
Published on 01 May 2026
Explanation
Use try-catch blocks to handle synchronous
errors
inside event handlers or functions in React.
This prevents the app from crashing and
allows graceful fallback handling β οΈ
Code:
function handleClick() {
try {
throw new Error('Something went wrong');
} catch (error) {
console.error(error.message);
}
}
Explanation
Handle errors in async API calls using
try-catch with async/await inside
useEffect or event
handlers. This helps display
user-friendly error messages
during failed requests π
Code:
//create state variables
async function fetchData() {
try
const res = await fetch('');
const result = await res.json();
setData(result);
} catch (err) {
setError('Failed to fetch data');
}
return error ? <p>{error}</p> : <div>
{JSON.stringify(data)}</div>;
}
Explanation
Use Error Boundaries to catch JavaScript
errors
in React component trees during rendering,
lifecycle
methods, and constructors.
This improves UI stability
and prevents full app crashes π‘οΈ
Code:
class ErrorBoundary extends React.Comonent {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
console.log(error, info);
}
render() {
if (this.state.hasError) {
return <h2>Something went wrong.</h2>;
}
return this.props.children;
}
}
Explanation
Handle form validation errors using
state variables
to
display error messages dynamically.
This improves
user experience and prevents
invalid submissions βοΈ
Code:
function FormComponent() {
const [error, setError] = useState('');
const handleSubmit = (e) => {
const name = e.target.name.value;
if (!name) {
setError('Name is required');
return;
}
setError('');
console.log('Form submitted');
};
return (
<form onSubmit={handleSubmit}>
<input name="name" />
<button type="submit">Submit</button>
{error && <p>{error}</p>}
</form>
);
}
Explanation
Use optional chaining and conditional
rendering to
prevent runtime errors caused by
undefined or
null values while accessing nested
objects
Code:
function Profile({ user }) {
return (
<div>
<h2>{user?.name}</h2>
<p>{user?.address?.city}</p>
</div>
);
}