What are error boundaries in ReactJS (16) ?
Runtime errors during rendering could put out an application in a broken state. React basically unmounts the hole react component tree. What would be great is if we could catch the errors anywhere in their component tree, log those errors, and display a fallback UI. This is where the error boundary takes the spotlight. A class component that implements either one or both of the life cycle methods static getDerivedStateFromError() or componentDidCatch() becomes an error boundary.The static getDerivedStateFromError() is used to render a fallback UI after an error is thrown. The componentDidCatch() is used to log the error information.
Error boundaries don’t catch errors for:
- Event handlers
- Asynchronous code (e.g. setTimeout or network request )
- Server Side rendering
- Errors thrown in the error boundary itself (rather than its children)
Let’s see an example without using Error Boundary.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app error-boundary-demo
Step 2: After creating your project folder i.e. error-boundary-demo, move to it using the following command:
Step 3: Create a directory and name it Component.
Project Structure: It will look like the following.
Step 4: In this step, we will create HeroViewar component to print the hero’s name. This component throws an error if hero’s name is ‘Joker’. Create HeroViewar.js in the Component directory and write down the following code.
Step 5: In this step, we will import HeroViewar from HeroViewar.js to print some hero’s name. Pass hero’s name as prop to HeroViewar component. Write down the following code in the App.js file.
Step to Run Application: Run the application using the following command from the root directory of the project:
Explanation: One of our hero’s name was ‘Joker’, that’s why HeroViewar throws an error. If you now take a look at the browser you will see the entire application crashes. Obviously, this is not good. What we want is if a particular component throws an error only that component should fall back into a UI and the remaining component should be unaffected.
Step 6: To overcome the above problem React 16 introduce a new concept of an “error boundary”. Error Boundary catch the errors anywhere in their component tree, and display a fallback UI. Let’s add it. Create ErrorBoundary.js in the Component directory and write down the following code.
Step 7: Update App.js to wrap each and every HeroViewar with ErrorBoundary like:
<ErrorBoundary> <HeroViewar name="..." /> </ErrorBoundary>
Write down the following code to App.js