
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
React JS Component Lifecycle Error Handling Phase
There are two main methods in error handling. These method are used in the error boundary mechanism in React. We wrap the component ( from where there is a possibility of error occurrences ) in a class which handles the below methods.
- Static method getDerivedStateFromError(error)
- componentDidCatch(error,info)
Static getDerivedStateFromError(error): As name of the method suggest, we can update state object here based on error received from descended component.
componentDidCatch(error, info): we can log the errors using api call. This is helpful in displaying useful error message on screen instead of technical errors.
A class can be termed as an error boundary if it implements at least one method from above two error handling lifecycle methods. Its main purpose is to show a fallback ui once we get an error.
If error is not cached by error boundary class then the entire react component tree below that component will be removed.
We can use the try catch in some methods but in application wide using error boundary is better standard. It keeps the declarative nature of react intact.
Please note − Error boundary feature works in production mode. In development mode it will display the actual errors directly on browser.