Error Handling in React Hooks
Errors and Exception Handling in React Hooks in 5 minutes
Error Handling in Hooks is quite Simple. In this article, we are going to demonstrate how to handle errors in React Hooks. We need to create a mechanism where, if the error occurs while working with a component, user should receive an Error Component rather than throwing a run time error from the component. We will be using React Hooks in order to achieve the desired functionality.
Error Handling Use Case Scenario
In this case rather than terminating the program unconditionally, which is the default behavior of the application, we will display an Error Component specifying a simple runtime error. The error Component that need to be displayed in given below.
This is the simple Component containing a header tag with the Error message, this component should be displayed once the user tried to divide the number by 0.
Throwing Error From the React Component
In the below code, we are creating a simple function which throws a custom error when the denominator is 0. In case when the code returns a custom error, we need to show the ErrorComponent instead of Normal Component.
Tracking Error Situation in case of Error
In case of Error, we can use a state variable to track the errors, In the below code, we have created a “hasError” state variable. As soon as the code enters the catch block, we can set this state variable to “true”
In the code above, we are calling getter function of “hasError” and assigning it to a value “true”. Now, at any time, if the value of this variable is set to true, we need to render the “ErrorComponent”.
When the setter “setHasError” is called and updated with the value “true”, the component tries to re-render. While Re-rendering, we can check if the variable value is true or false. If the value is true, render “ErrorComponent”. See the implementation below for the template code.
In the above code, we can see that if the value of “hasError” is true, we are rendering the “ErrorComponent”, else the normal HTML to take the user input and show the division output is displayed.
Getting it all Together
Now lets try to bring all these building blocks together. The building block for the code comprises of:
- State variable for “numerator”, “denominator” and “executionOutput”
- State Variable to track error Condition “hasError”
- As soon as the error condition arrives, “hasError” marked as true
- if “hasError” is true, render “ErrorComponent”
- If “hasError” is false, render the normal component to take user input
The entire code is given below:
You can try to update the editor code and try some real time scenario:
Error and Exception handling is an easy task in React. You can also access the following URL for more updates: