How to Catch Errors During Rendering in React
When building a react application errors are bound to happen in our applications, whether they’re server-related errors or edge cases. As such, many methods have been developed to prevent these errors from interfering with the user and developer experience. In React, one such method is the use of error boundaries.
What are Error Boundaries?
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.source: official react js website
To solve this problem for React users, React 16 introduces a new concept of an “error boundary”. There are limits to the built-in error boundary in React 16v but in this case, we can use a package called react-error-boundary, Let's build a small project to explain the concept behind error boundary.
- Note: We will be covering a few advanced concepts of React. So having intermediate knowledge of React is advisable.
Let Us Go Through The React Built-in Error boundary.
The built-in error boundary can't catch errors for Event handlers, Asynchronous code, Server-side rendering, and Errors thrown in the error boundary itself.
What are event handlers? An event handler is a callback routine that operates asynchronously once an event takes place.
What is asynchronous code? Asynchronous programming is a technique that enables your program to start a potentially long-running task and still be able to be responsive to other events while that task runs, rather than having to wait until that task has finished. Once that task has finished, your program is presented with the result. Source
What is server-side rendering? Server-side rendering refers to an application’s ability to display the web page on the server rather than rendering it in the browser. When a website’s JavaScript is rendered on the website’s server, a fully rendered page is sent to the client and the client’s JavaScript bundle engages and enables the Single Page Application framework to operate. Source
while Error thrown
lets you indicate that something unexpected happened and the normal flow of execution can't continue.
Let's code
Facing errors in your react applications, we can see error logs like this in development.
The user won't be seeing error logs but white screens just like this.
So how can we handle these types of errors in your code by using a method called Error boundaries in react?
The built-in way
- Create a file called builtInErrorBoundary.js in your src folder copy and paste this code inside it.
import { Component } from "react";
export class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = {
hasError: false
};
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.log("log errors Info", error, errorInfo);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
- To catch errors during rendering we just need to wrap this with our main component pages just like this
import React, { useState } from "react";
import { ErrorBoundary } from "./builtInErrorBoundary";
import ProfileCard from "./component/profile";
import "./styles.css";
export default function App() {
const [ageState, setAgeState] = useState(1);
const incrementYourAge = () => setAgeState(ageState + 1);
return (
<ErrorBoundary>
<div className="App">
<div className="container">
<ProfileCard ageState={"10"} />
{/* try this to see the Something went wrong screen
<ProfileCard ageState={{}} />
*/}
<button onClick={incrementYourAge}>
<h3>Click here to state your age</h3>
</button>
</div>
</div>
</ErrorBoundary>
);
}
Check out the live code:
- You can check out the below code sandbox for complete code and the file structure may not be the best.
What the user can see is your custom fallback UI something like this when an error accords, you can make the design better like a 404 page.
The Best Way To Go About Error Boundaries For Your Next Big Project.
I explained that the built-in error boundary can't catch errors for Event handlers, Asynchronous code, Server-side rendering, and Errors thrown in the error boundary itself.
So what can we do about this problem, there are two ways to solve this problem
- Building your error boundaries boilerplate for all the solutions you need which will take time
- By using an open-source npm package called react-error-boundary which solves all our problems by just installing the package (Thanks to the creators of this package).
This component provides a simple and reusable wrapper that you can use to wrap around your components. Any rendering errors in your components hierarchy can then be gracefully handled.
For Example :
import {ErrorBoundary} from 'react-error-boundary'
function ErrorFallback({error, resetErrorBoundary}) {
return (
<div>
<p>Something went wrong:</p>
<span>{error.message}</pre>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
)
}
export default function DashboardPage () {
function errorHandler(error, errorInfo) {
console.error("log", error, errorInfo);
}
return (
<ErrorBoundary
FallbackComponent={ErrorFallback}
onError={errorHandler}>
onReset={() => {
// reset the state of your app so the error doesn't happen again
}}
>
<div>
<h3>Welcome back David</h3>
</div>
</ErrorBoundary>
)
}
What's next?
Now you know the basics of Error Boundaries. You know what it is, and why it can be useful, even how to apply it in your react application. But nothing will convince you more than some hands-on experience. This package makes it easy and faster, how to handle Error Boundaries Learn more here. ✌️
Thank you for reading
Feel free to subscribe to my email newsletter and Connect with me