Any application is prone to runtime errors. These could be various kinds of errors: caused by bugs, unexpected input, validation errors, poor network connectivity, or server errors. Lots of them. A well-designed app must not silently stop working or display an ugly error message with tons of irrelevant technical information. Instead, it must always display some meaningful error information, short and simple, and provide tips on how to solve the problem.
There are various approaches to error handling in React apps; let’s review them. As an example, we will look at a failed network request.
First, and simplest, is to store the error in the state of the component. Whenever we make a server request, we can surround it in a try-catch block and store the error in state or in initial props:
import React from "react";