Error handling with React

Even if we write excellent code and we cover all the code with tests, errors will still happen. The different browsers and environments, and real user data, are all variables that we cannot control and sometimes our code will fail. As developers, that is something we must accept.

The best thing we can do when problems happen in our applications is:

  • Notify the users and help them understand what happened and what they should do
  • Collect all useful information about the error and the state of the application in order to reproduce it and fix bugs quickly

The way React handle errors is slightly counter-intuitive in the beginning.

Suppose you have the following components:

const Nice => <div>Nice</div> 

And:

const Evil => ( <div> Evil ...

Get React Design Patterns and Best Practices now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.