PageSourceSearch

https://refine.dev/assets/js/4946e2a5.9e5306c7.js

js refine.dev collected 2026-10-02 16:35:40 UTC 43,031 bytes, 1 lines download raw bytes

1"use strict";(self.webpackChunkdocumentation=self.webpackChunkdocumentation||[]).push([[2327],{58860:(e,r,n)=>{n.d(r,{xA:()=>p,yg:()=>h});var t=n(37953);function a(e,r,n){return r in e?Object.defineProperty(e,r,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[r]=n,e}function o(e,r){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var t=Object.getOwnPropertySymbols(e);r&&(t=t.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),n.push.apply(n,t)}return n}function i(e){for(var r=1;r<arguments.length;r++){var n=null!=arguments[r]?arguments[r]:{};r%2?o(Object(n),!0).forEach((function(r){a(e,r,n[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):o(Object(n)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))}))}return e}function l(e,r){if(null==e)return{};var n,t,a=function(e,r){if(null==e)return{};var n,t,a={},o=Object.keys(e);for(t=0;t<o.length;t++)n=o[t],r.indexOf(n)>=0||(a[n]=e[n]);return a}(e,r);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(t=0;t<o.length;t++)n=o[t],r.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}var s=t.createContext({}),c=function(e){var r=t.useContext(s),n=r;return e&&(n="function"==typeof e?e(r):i(i({},r),e)),n},p=function(e){var r=c(e.components);return t.createElement(s.Provider,{value:r},e.children)},d="mdxType",u={inlineCode:"code",wrapper:function(e){var r=e.children;return t.createElement(t.Fragment,{},r)}},g=t.forwardRef((function(e,r){var n=e.components,a=e.mdxType,o=e.originalType,s=e.parentName,p=l(e,["components","mdxType","originalType","parentName"]),d=c(n),g=a,h=d["".concat(s,".").concat(g)]||d[g]||u[g]||o;return n?t.createElement(h,i(i({ref:r},p),{},{components:n})):t.createElement(h,i({ref:r},p))}));function h(e,r){var n=arguments,a=r&&r.mdxType;if("string"==typeof e||a){var o=n.length,i=new Array(o);i[0]=g;var l={};
1for(var s in r)hasOwnProperty.call(r,s)&&(l[s]=r[s]);l.originalType=e,l[d]="string"==typeof e?e:a,i[1]=l;for(var c=2;c<o;c++)i[c]=n[c];return t.createElement.apply(null,i)}return t.createElement.apply(null,n)}g.displayName="MDXCreateElement"},47470:(e,r,n)=>{n.r(r),n.d(r,{assets:()=>p,contentTitle:()=>s,default:()=>h,frontMatter:()=>l,metadata:()=>c,toc:()=>d});n(37953);var t=n(58860);function a(e,r,n){return r in e?Object.defineProperty(e,r,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[r]=n,e}function o(e,r){return r=null!=r?r:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):function(e,r){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var t=Object.getOwnPropertySymbols(e);r&&(t=t.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),n.push.apply(n,t)}return n}(Object(r)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})),e}function i(e,r){if(null==e)return{};var n,t,a=function(e,r){if(null==e)return{};var n,t,a={},o=Object.keys(e);for(t=0;t<o.length;t++)n=o[t],r.indexOf(n)>=0||(a[n]=e[n]);return a}(e,r);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(t=0;t<o.length;t++)n=o[t],r.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}const l={title:"Error Boundaries in React -  Handling Errors Gracefully",description:"We'll see how to handle errors in React using Error Boundaries and how to use the react-error-boundary library to handle errors in React.",slug:"react-error-boundaries",authors:"chidume_nnamdi",category:"Engineering",tags:["react","bugs"],image:"https://refine.ams3.cdn.digitaloceanspaces.com/blog-yearly/2023/2023-11-09-react-error-bounderies/social-2.png",hide_table_of_contents:!1,last_update:new Date("2024-09-10T00:00:00.000Z")},s=void 0,c={permalink:"/blog/react-error-boundaries",source:"@site/blog/2024-09-09-react-error-boundaries.md",title:"Error Boundaries in React -  Handling Errors Gracefully",description:"We'll see how to handle errors in React using Error Boundaries and how to use the react-error-boundary library to handle errors in React.",date:"2024-09-09T00:00:00.000Z",formattedDate:"SEP 9, 2024",tags:[{label:"react",permalink:"/blog/tags/react"},{label:"bugs",permalink:"/blog/tags/bugs"}],readingTime:16.43,hasTruncateMarker:!1,authors:[{name:"Chidume Nnamdi",title:"Software Engineer",url:"https://github.com/philipszdavido",imageURL:"https://github.com/philipszdavido.png",key:"chidume_nnamdi"}],frontMatter:{title:"Error Boundaries in React -  Handling Errors Gracefully",description:"We'll see how to handle errors in React using Error Boundaries and how to use the react-error-boundary library to handle errors in React.",slug:"react-error-boundaries",authors:"chidume_nnamdi",category:"Engineering",tags:["react","bugs"],image:"https://refine.ams3.cdn.digitaloceanspaces.com/blog-yearly/2023/2023-11-09-react-error-bounderies/social-2.png",hide_table_of_contents:!1,last_update:"2024-09-10T00:00:00.000Z"},prevItem:{title:"Introduction to Mantine UI",permalink:"/blog/mantine-ui-react"},nextItem:{title:"Introduction to HTMX",permalink:"/blog/what-is-htmx"},lastUpdate:"2024-09-10T00:00:00.000Z",formattedLastUpdateDate:"SEP 10, 2024",relatedPosts:[{title:"How to Multipart File Upload Using FormData with React Hook Form",description:"In this guide, I'm going to show you how to multipart files upload with using React Hook Form",permalink:"/blog/how-to-multipart-file-upload-with-react-hook-form",authors:[{name:"Melih Ekinci",title:"Frontend Developer",url:"https://github.com/mlhekinci",imageURL:"https://github.com/mlhekinci.png",key:"melih"}],readingTime:7.115,date:"2022-03-29T00:00:00.000Z",formattedDate:"MAR 29, 2022",lastUpdate:"2022-10-19T00:00:00.000Z",formattedLastUpdateDate:"OCT 19, 2022"},{title:"How to set up a WebSocket connection with Node.js and React.js?",description:"Understanding Real-time communication with React and WebSocket",permalink:"/blog/react-websocket-tutorial-nodejs",authors:[{name:"Frank Joseph",title:"Software Developer",imageURL:"/img/generic-profile.png",key:"frank_joseph"}],readingTime:18.785,date:"2024-08-15T00:00:00.000Z",formattedDate:"AUG 15, 2024",lastUpdate:"2024-08-15T00:00:00.000Z",formattedLastUpdateDate:"AUG 15, 2024"},{title:"How to use Zustand",description:"We'll learn how to use Zustand in our React project.",permalink:"/blog/zustand-react-state",authors:[{name:"Chidume Nnamdi",title:"Software Engineer",url:"https://github.com/philipszdavido",imageURL:"https://github.com/philipszdavido.png",key:"chidume_nnamdi"}
1],readingTime:18.215,date:"2024-07-31T00:00:00.000Z",formattedDate:"JUL 31, 2024",lastUpdate:"2024-08-02T00:00:00.000Z",formattedLastUpdateDate:"AUG 2, 2024"}],authorPosts:[{title:"GraphQL vs REST - Key Differences and Use Cases",description:"We'll explore the key differences between GraphQL and REST, and discuss the use cases where each approach excels.",permalink:"/blog/graphql-vs-rest",authors:[{name:"Chidume Nnamdi",title:"Software Engineer",url:"https://github.com/philipszdavido",imageURL:"https://github.com/philipszdavido.png",key:"chidume_nnamdi"}],readingTime:18.16,date:"2024-09-12T00:00:00.000Z",formattedDate:"SEP 12, 2024",lastUpdate:"2024-09-12T00:00:00.000Z",formattedLastUpdateDate:"SEP 12, 2024"},{title:"How to use Zustand",description:"We'll learn how to use Zustand in our React project.",permalink:"/blog/zustand-react-state",authors:[{name:"Chidume Nnamdi",title:"Software Engineer",url:"https://github.com/philipszdavido",imageURL:"https://github.com/philipszdavido.png",key:"chidume_nnamdi"}],readingTime:18.215,date:"2024-07-31T00:00:00.000Z",formattedDate:"JUL 31, 2024",lastUpdate:"2024-08-02T00:00:00.000Z",formattedLastUpdateDate:"AUG 2, 2024"},{title:"A Guide on React Lazy Loading",description:"We will be looking at what lazy loading is, how it works, and how it can be used to improve the performance of React applications.",permalink:"/blog/react-lazy-loading",authors:[{name:"Chidume Nnamdi",title:"Software Engineer",url:"https://github.com/philipszdavido",imageURL:"https://github.com/philipszdavido.png",key:"chidume_nnamdi"}],readingTime:15.82,date:"2024-07-12T00:00:00.000Z",formattedDate:"JUL 12, 2024",lastUpdate:"2024-07-12T00:00:00.000Z",formattedLastUpdateDate:"JUL 12, 2024"}],category:{value:"Engineering",label:"Engineering",permalink:"/blog/categories/engineering"}},p={authorsImageUrls:[void 0]},d=[{value:"Introduction",id:"introduction",level:2},{value:"What Are React Error Boundaries?",id:"what-are-react-error-boundaries",level:2},{value:"Basic Usage of Error Boundaries",id:"basic-usage-of-error-boundaries",level:2},{value:"Error Boundary Limitations",id:"error-boundary-limitations",level:2},{value:"Handling errors using <code>react-error-boundary</code> library",id:"handling-errors-using-react-error-boundary-library",level:2},{value:"How Error Boundaries are Used for Logging and Reporting Errors",id:"how-error-boundaries-are-used-for-logging-and-reporting-errors",level:2},{value:"Resetting your app after an Error",id:"resetting-your-app-after-an-error",level:2},{value:"FallbackComponent prop",id:"fallbackcomponent-prop",level:2},{value:"Bonus: Best Practices for Error Boundaries",id:"bonus-best-practices-for-error-boundaries",level:2},{value:"Use Error Boundaries Strategically",id:"use-error-boundaries-strategically",level:4},{value:"Pick the Right Fallback UI",id:"pick-the-right-fallback-ui",level:4},{value:"Granularity Matters",id:"granularity-matters",level:4},{value:"Logging and Monitoring",id:"logging-and-monitoring",level:4},{value:"Consider Using Libraries for Error Boundaries",id:"consider-using-libraries-for-error-boundaries",level:4},{value:"Testing Your Error Boundaries",id:"testing-your-error-boundaries",level:4},{value:"Error Boundaries for Third-Party Components",id:"error-boundaries-for-third-party-components",level:4},{value:"Avoid Overuse",id:"avoid-overuse",level:4},{value:"Reset State On Error",id:"reset-state-on-error",level:4},{value:"Dealing with Errors in Asynchronous Operations in React**",id:"dealing-with-errors-in-asynchronous-operations-in-react",level:2}],u={toc:d},g="wrapper";function h(e){var{components:r}=e,n=i(e,["components"]);return(0,t.yg)(g,o(function(e){for(var r=1;r<arguments.length;r++){var n=null!=arguments[r]?arguments[r]:{},t=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(t=t.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),t.forEach((function(r){a(e,r,n[r])}))}return e}({},u,n),{components:r,mdxType:"MDXLayout"}),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"This article was last updated on September 09, 2024, to add sections on Advanced Error Logging, Best Practices and Handling Asynchronous Errors in React Error Boundaries.")),(0,t.yg)("h2",{id:"introduction"},"Introduction"),(0,t.yg)("p",null,"React, a popular JavaScript library for building user interfaces offers a powerful tool called Error Boundaries. These Error Boundaries serve as a safety net for React applications, allowing developers to gracefully catch and manage errors, preventing them from propagating up the component tree and causing application crashes."),
1(0,t.yg)("p",null,"Developers can utilize Error Boundaries to present users with informative error messages, log error specifics to aid in debugging, and ensure the application remains resilient even in the face of unforeseen challenges. In the forthcoming sections, we will investigate the critical role of error handling and examine how React Error Boundaries can elevate the user experience by serving as a protective shield for your application."),(0,t.yg)("h2",{id:"what-are-react-error-boundaries"},"What Are React Error Boundaries?"),(0,t.yg)("p",null,"In JavaScript, we use the ",(0,t.yg)("inlineCode",{parentName:"p"},"try...catch")," statement to catch errors."),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-tsx"},"try {\n  // code that may throw an error\n} catch (error) {\n  // code to handle the error\n}\n")),(0,t.yg)("p",null,"We put the fragile code inside the ",(0,t.yg)("inlineCode",{parentName:"p"},"try")," block, and if an error occurs, we catch it in the ",(0,t.yg)("inlineCode",{parentName:"p"},"catch")," block. This fragile code is a code we are unsure that there might be undefined or null occurring and we don't want the whole program stopping, so we enclose them in the ",(0,t.yg)("inlineCode",{parentName:"p"},"try")," block. The ",(0,t.yg)("inlineCode",{parentName:"p"},"catch")," block is where we handle the error. It is there that we can display a message to the user or log the error to the console."),(0,t.yg)("p",null,"You will find this ",(0,t.yg)("inlineCode",{parentName:"p"},"try...catch")," statement very useful when working with imperative code, and you don't want your users to see their app breaking down in the middle of usage.\nHowever, this approach is not suitable for React applications, as it only works for imperative code. React applications are declarative, meaning they are composed of components that render based on the state of the application. Therefore, we need a different approach for handling errors in React applications."),(0,t.yg)("p",null,"The concept of Error Boundaries in React was introduced in version 16 of the library. Before the introduction of Error Boundaries, errors in React components were challenging to handle gracefully. When an error occurs within a component, it could potentially corrupt the entire component tree, leading to a broken user interface and a poor user experience.\nReact Error Boundary is like the ",(0,t.yg)("inlineCode",{parentName:"p"},"try..catch")," of React. It is a React component that catches JavaScript errors anywhere in its child component tree, logs those errors, and displays a fallback UI instead of the component tree that crashed.\nSee a component tree below:"),(0,t.yg)("div",{className:"centered-image"},(0,t.yg)("img",{src:"https://refine.ams3.cdn.digitaloceanspaces.com/blog-yearly/2023/2023-11-09-react-error-bounderies/1.jpeg",alt:"mojo framework"})),(0,t.yg)("br",null),(0,t.yg)("p",null,(0,t.yg)("inlineCode",{parentName:"p"},"root")," is the root component of the component tree. It is the parent of ",(0,t.yg)("inlineCode",{parentName:"p"},"COMP I")," and ",(0,t.yg)("inlineCode",{parentName:"p"},"COMP II"),". ",(0,t.yg)("inlineCode",{parentName:"p"},"COMP I")," is the parent of ",(0,t.yg)("inlineCode",{parentName:"p"},"COMP III")," and ",(0,t.yg)("inlineCode",{parentName:"p"},"COMP IV"),". ",(0,t.yg)("inlineCode",{parentName:"p"},"COMP III")," is the parent of ",(0,t.yg)("inlineCode",{parentName:"p"},"COMP V"),". ",(0,t.yg)("inlineCode",{parentName:"p"},"COMP IV")," is the parent component of ",(0,t.yg)("inlineCode",{parentName:"p"},"COMP VI"),". ",(0,t.yg)("inlineCode",{parentName:"p"},"COMP I"),", ",(0,t.yg)("inlineCode",{parentName:"p"},"COMP II"),", ",(0,t.yg)("inlineCode",{parentName:"p"},"COMP III"),", and ",(0,t.yg)("inlineCode",{parentName:"p"},"COMP IV")," are leaf components."),(0,t.yg)("p",null,"If an error occurs in ",(0,t.yg)("inlineCode",{parentName:"p"},"COMP V"),", it will propagate up the component tree to ",(0,t.yg)("inlineCode",{parentName:"p"},"COMP III"),", then to ",(0,t.yg)("inlineCode",{parentName:"p"},"COMP I"),", and finally to ",(0,t.yg)("inlineCode",{parentName:"p"},"root"),". If there is no error boundary in the component tree, the entire component tree will be corrupted, and the application will crash."),(0,t.yg)("div",{className:"centered-image"},(0,t.yg)("img",{src:"https://refine.ams3.cdn.digitaloceanspaces.com/blog-yearly/2023/2023-11-09-react-error-bounderies/2.jpeg",alt:"mojo framework"})),(0,t.yg)("br",null),(0,t.yg)("div",{className:"centered-image"},(0,t.yg)("img",{src:"https://refine.ams3.cdn.digitaloceanspaces.com/blog-yearly/2023/2023-11-09-react-error-bounderies/3.jpeg",alt:"mojo framework"})),(0,t.yg)("br",null),(0,t.yg)("p",null,"However, if there is an error boundary in the component tree, it will catch the error and display a fallback UI instead of the component tree that crashed."),(0,t.yg)("div",{className:"centered-image"},(0,t.yg)("img",{src:"https://refine.ams3.cdn.digitaloceanspaces.com/blog-yearly/2023/2023-11-09-react-error-bounderies/4.jpeg",alt:"mojo framework"})),(0,t.yg)("br",null),(0,t.yg)("p",null,"Here, the error boundary is ",(0,t.yg)("inlineCode",{parentName:"p"},"COMP III"),". It catches the error that occurred in ",(0,t.yg)("inlineCode",{parentName:"p"},"COMP V")," and displays a fallback UI instead of the component tree that crashed. The error and crash do not propagate up the component tree to ",(0,t.yg)("inlineCode",{parentName:"p"},"COMP I")," and ",(0,t.yg)("inlineCode",{parentName:"p"},"root"),". We see now the benefit of React Error Boundary."),(0,t.yg)("p",null,"Error Boundaries are React components that implement the ",(0,t.yg)("inlineCode",{parentName:"p"},"componentDidCatch")," lifecycle method. This method is invoked after an error has been thrown by a de
1scendant component. It receives two arguments: ",(0,t.yg)("inlineCode",{parentName:"p"},"error")," and ",(0,t.yg)("inlineCode",{parentName:"p"},"info"),". The ",(0,t.yg)("inlineCode",{parentName:"p"},"error")," argument is the error that was thrown, while the ",(0,t.yg)("inlineCode",{parentName:"p"},"info")," argument is an object that contains a component stack trace."),(0,t.yg)("h2",{id:"basic-usage-of-error-boundaries"},"Basic Usage of Error Boundaries"),(0,t.yg)("p",null,"In the last section, we said that Error Boundaries are React components that implement the ",(0,t.yg)("inlineCode",{parentName:"p"},"componentDidCatch")," lifecycle method. A lifecycle method is a special method in a React Component that is invoked at a particular stage in the lifecycle of the component."),(0,t.yg)("blockquote",null,(0,t.yg)("p",{parentName:"blockquote"},"The ",(0,t.yg)("inlineCode",{parentName:"p"},"componentDidCatch")," lifecycle method is invoked after an error has been thrown by a descendant component.")),(0,t.yg)("p",null,"There are different stages in the lifecycle of a component in React. The stages are: ",(0,t.yg)("inlineCode",{parentName:"p"},"initialization"),", ",(0,t.yg)("inlineCode",{parentName:"p"},"mounting"),", ",(0,t.yg)("inlineCode",{parentName:"p"},"updating"),", and ",(0,t.yg)("inlineCode",{parentName:"p"},"unmounting"),". The ",(0,t.yg)("inlineCode",{parentName:"p"},"componentDidCatch")," lifecycle method is invoked during the ",(0,t.yg)("inlineCode",{parentName:"p"},"updating")," stage of the component lifecycle.\nThis method is invoked after an error has been thrown by a descendant component. It receives two arguments: ",(0,t.yg)("inlineCode",{parentName:"p"},"error")," and ",(0,t.yg)("inlineCode",{parentName:"p"},"info"),"."),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"The ",(0,t.yg)("inlineCode",{parentName:"li"},"error")," argument is the error that was thrown."),(0,t.yg)("li",{parentName:"ul"},"The ",(0,t.yg)("inlineCode",{parentName:"li"},"info")," argument is an object that contains a component stack trace.")),(0,t.yg)("p",null,"Let's see a simple example of an Error Boundary."),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-tsx"},'import React from "react";\n\nclass ErrorBoundary extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = { hasError: false };\n  }\n\n  componentDidCatch(error, info) {\n    this.setState({ hasError: true });\n    console.log(error, info);\n  }\n\n  render() {\n    if (this.state.hasError) {\n      return <h1>Something went wrong.</h1>;\n    }\n    return this.props.children;\n  }\n}\n')),(0,t.yg)("p",null,"There are things we need to learn here. See that in the ",(0,t.yg)("inlineCode",{parentName:"p"},"componentDidCatch")," method it receives two arguments as we have known. The ",(0,t.yg)("inlineCode",{parentName:"p"},"error")," and ",(0,t.yg)("inlineCode",{parentName:"p"},"info")," arguments. We set the ",(0,t.yg)("inlineCode",{parentName:"p"},"hasError")," property of the state to ",(0,t.yg)("inlineCode",{parentName:"p"},"true")," in the ",(0,t.yg)("inlineCode",{parentName:"p"},"componentDidCatch")," method. We also log the error and info to the console. We will see the use of the ",(0,t.yg)("inlineCode",{parentName:"p"},"hasError")," property later.\nThis is a basic usage of an Error Boundary. We will see how to use it in a React application."),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"Handling Different Types of Errors")),(0,t.yg)("p",null,"In React, we can create components from a function or a class. We call them functional components and class components respectively. React Error Boundaries are only created from class components because they implement the ",(0,t.yg)("inlineCode",{parentName:"p"},"componentDidCatch")," lifecycle method. There is no way to implement ",(0,t.yg)("inlineCode",{parentName:"p"},"componentDidCatch")," lifecycle method in functional components for now. React can come up with their magic in the future where we can be able to create an Error Boundary in functional components but for now, we can only do that in the class components."),(0,t.yg)("p",null,"We stated in the last section that a React Error Boundary is created when a class component implements the ",(0,t.yg)("inlineCode",{parentName:"p"},"componentDidCatch")," lifecycle method. A class component can also be an Error Boundary if it defines either (or both) of the lifecycle methods ",(0,t.yg)("inlineCode",{parentName:"p"},"static getDerivedStateFromError()")," or ",(0,t.yg)("inlineCode",{parentName:"p"},"componentDidCatch()"),"."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"static getDerivedStateFromError()")," lifecycle method is invoked after an error has been thrown by a de
1scendant component. It receives the error that was thrown as an argument and should return a value to update state."),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-tsx"},"static getDerivedStateFromError(error) {\n    // Update state so the next render will show the fallback UI.\n    return { hasError: true };\n}\n")),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"getDerivedStateFromError"),"is used to render a fallback UI after an error has been thrown by a descendant component. The ",(0,t.yg)("inlineCode",{parentName:"p"},"componentDidCatch")," lifecycle method is used to log the error information."),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-tsx"},"componentDidCatch(error, info) {\n    // You can also log the error to an error-reporting service\n    logErrorToMyService(error, info);\n}\n")),(0,t.yg)("p",null,"Example:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-tsx"},'import React from "react";\n\nclass ErrorBoundary extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = { hasError: false };\n  }\n\n  static getDerivedStateFromError(error) {\n    // Update state so the next render will show the fallback UI.\n    return { hasError: true };\n  }\n\n  componentDidCatch(error, info) {\n    // You can also log the error to an error-reporting service\n    logErrorToMyService(error, info);\n  }\n\n  render() {\n    if (this.state.hasError) {\n      // You can render any custom fallback UI\n      return <h1>Something went wrong.</h1>;\n    }\n\n    return this.props.children;\n  }\n}\n')),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"getDerivedStateFromError"),' method is called during the "render" phase, so side effects are not permitted. For those use cases, use the ',(0,t.yg)("inlineCode",{parentName:"p"},"componentDidCatch")," lifecycle method instead. In the ",(0,t.yg)("inlineCode",{parentName:"p"},"componentDidCatch")," method, we can log the error to an error reporting service. We can also use it to perform side effects. We will see how to do that later."),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-tsx"},"<ErrorBoundary>\n  <MyComponent />\n</ErrorBoundary>\n")),(0,t.yg)("p",null,"The code above is an example of how to use an Error Boundary in a React application. We wrap the component we want to catch errors from in the Error Boundary component. In this case, we wrap the ",(0,t.yg)("inlineCode",{parentName:"p"},"MyComponent")," component in the ",(0,t.yg)("inlineCode",{parentName:"p"},"ErrorBoundary")," component. If an error occurs in the ",(0,t.yg)("inlineCode",{parentName:"p"},"MyComponent")," component, it will be caught by the ",(0,t.yg)("inlineCode",{parentName:"p"},"ErrorBoundary")," component."),(0,t.yg)("p",null,"This is akin to ",(0,t.yg)("inlineCode",{parentName:"p"},"try...catch")," in JavaScript:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-tsx"},"try {\n  MyComponent();\n} catch (error) {\n  // code to handle the error\n}\n")),(0,t.yg)("h2",{id:"error-boundary-limitations"},"Error Boundary Limitations"),(0,t.yg)("p",null,"We have seen throughout this post the beauty of handling errors in React using Error Boundary but the downside is that not all errors can be caught by Error Boundary. Some errors cannot be caught by Error Boundary. We will see them in this section."),(0,t.yg)("p",null,"Error Boundaries do not catch errors for:"),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"Event handlers")),(0,t.yg)("p",null,"Event handlers inside React components are not known by React, they are functions to be called when an event happens. they are handled by the browser DOM. Therefore, if an error occurs in an event handler, it will not be caught by the Error Boundary."),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"Asynchronous code")),(0,t.yg)("p",null,"Asynchronous code (e.g. ",(0,t.yg)("inlineCode",{parentName:"p"},"setTimeout")," or ",(0,t.yg)("inlineCode",{parentName:"p"},"requestAnimationFrame")," callbacks) same thing as Event handlers are not caught by React so the Error Boundary cannot catch them to deal with them."),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"Server-side rendering")),(0,t.yg)("p",null,"Error boundaries are specific to the client side and won't catch errors that occur on the server or in server-side rendering. Server errors should be handled on the server and communicated to the client."),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"Errors in Error Boundary component")),(0,t.yg)("p",null,"Errors thrown in the error boundary itself (rather than 
1its children) cannot be handled by the Error boundary, it is a component also, so we should take great care when writing our error boundary component."),(0,t.yg)("p",null,"Error boundaries can help display a fallback UI, but they don't inherently manage the error state of your application. You need to implement your own error state management and recovery strategies."),(0,t.yg)("h2",{id:"handling-errors-using-react-error-boundary-library"},"Handling errors using ",(0,t.yg)("inlineCode",{parentName:"h2"},"react-error-boundary")," library"),(0,t.yg)("p",null,"Error handling business in React has been simplified by a great library called ",(0,t.yg)("a",{parentName:"p",href:"https://www.npmjs.com/package/react-error-boundary"},"react-error-boundary"),". It is a reusable React error boundary component. Supports all React renderers (including React DOM and React Native)."),(0,t.yg)("p",null,"To use it, we need to install it via npm or yarn:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre"},"npm install react-error-boundary\n")),(0,t.yg)("p",null,"Then we import it in our React application:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-tsx"},'import { ErrorBoundary } from "react-error-boundary";\n')),(0,t.yg)("p",null,"With this library, we do not need to create a React Error Boundary component. the library has done that for us. We only need to use it in our React application. ",(0,t.yg)("inlineCode",{parentName:"p"},"react-error-boundary")," exposes an ErrorBoundary component, which supports several props to help you build an error boundary component with no effort."),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-tsx"},"<ErrorBoundary fallback={<div>Something went wrong</div>}>\n  <ExampleApplication />\n</ErrorBoundary>\n")),(0,t.yg)("p",null,"You see how simple it is. Just wrap the component you want to catch errors from in the ErrorBoundary component. The ",(0,t.yg)("inlineCode",{parentName:"p"},"fallback")," prop is the UI to render when there is an error. It can be a React component or a function that returns a React component."),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"ErrorBoundary")," component has some useful that we can use to render UI fallback or get some errors."),(0,t.yg)("p",null,(0,t.yg)("strong",{parentName:"p"},"fallbackRender")),(0,t.yg)("p",null,"This ",(0,t.yg)("inlineCode",{parentName:"p"},"fallbackRender")," is a Render prop passed to the ",(0,t.yg)("inlineCode",{parentName:"p"},"ErrorBoundary"),". The ",(0,t.yg)("inlineCode",{parentName:"p"},"fallbackRender")," prop is a function, it is called when an error occurs and the return value is a JSX that is rendered in place of the misbehaving component."),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-tsx"},'function fallbackRender({ error, resetErrorBoundary }) {\n  return (\n    <div role="alert">\n      <p>Something went wrong:</p>\n      <pre style={{ color: "red" }}>{error.message}</pre>\n    </div>\n  );\n}\n\n<ErrorBoundary fallbackRender={fallbackRender}>\n  <ExampleApplication />\n</ErrorBoundary>;\n')),(0,t.yg)("p",null,"See that the render prop is called with an object that destructs to ",(0,t.yg)("inlineCode",{parentName:"p"},"error")," and ",(0,t.yg)("inlineCode",{parentName:"p"},"resetErrorBoundary"),". The ",(0,t.yg)("inlineCode",{parentName:"p"},"error")," is the error message details and the ",(0,t.yg)("inlineCode",{parentName:"p"},"resetErrorBoundary")," is a function that can be called to reset the error boundary and retry the render."),(0,t.yg)("h2",{id:"how-error-boundaries-are-used-for-logging-and-reporting-errors"},"How Error Boundaries are Used for Logging and Reporting Errors"),(0,t.yg)("p",null,"I was just thinking that we could share some thoughts on the effective way to log and report errors when using React Error Boundaries in our app."),(0,t.yg)("p",null,"When an error occurs in a component that's inside an error boundary, we have the opportunity to do more than show a fallback UI. We also want to log these errors to a service so that we can keep track of issues and fix them quickly."),(0,t.yg)("p",null,"We can place a logging mechanism inside the ",(0,t.yg)("inlineCode",{parentName:"p"},"componentDidCatch")," method to send error details and component stack traces to 
1some error tracking service, as shown in the following simple example:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-jsx"},"class ErrorBoundary extends React.Component {\n  componentDidCatch(error, info) {\n    // Post the error to a service\n    logErrorToMyService(error, info);\n  }\n\n  render() {\n    if (this.state.hasError) {\n      return <h1>Something went wrong.</h1>;\n    }\n\n    return this.props.children;\n  }\n}\n")),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"logErrorToMyService")," function would send the error details to our preferred error tracking service, enabling us to monitor the issues in real-time. That way, we'll know what's going wrong behind the scenes, even if the UI doesn't crash."),(0,t.yg)("h2",{id:"resetting-your-app-after-an-error"},"Resetting your app after an Error"),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"react-error-boundary")," provides us with a prop ",(0,t.yg)("inlineCode",{parentName:"p"},"onReset")," which we can use to reset our component when an error is thrown."),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-tsx"},'function fallbackRender({ error, resetErrorBoundary }) {\n  return (\n    <div role="alert">\n      <p>Something went wrong:</p>\n      <pre style={{ color: "red" }}>{error.message}</pre>\n    </div>\n  );\n}\n\n<ErrorBoundary\n  fallbackRender={fallbackRender}\n  onReset={() => {\n    // reset the state of your app so the error doesn\'t happen again\n  }}\n>\n  <ExampleApplication />\n</ErrorBoundary>;\n')),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"onReset")," is called when the ",(0,t.yg)("inlineCode",{parentName:"p"},"resetErrorBoundary")," function is called. The ",(0,t.yg)("inlineCode",{parentName:"p"},"resetErrorBoundary")," function is passed to the ",(0,t.yg)("inlineCode",{parentName:"p"},"fallbackRender")," function as a parameter.\nWe can now add a button in the JSX returned by the ",(0,t.yg)("inlineCode",{parentName:"p"},"fallbackRender")," function to reset the error boundary."),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-tsx"},'function fallbackRender({ error, resetErrorBoundary }) {\n  return (\n    <div role="alert">\n      <p>Something went wrong:</p>\n      <pre style={{ color: "red" }}>{error.message}</pre>\n      <button onClick={resetErrorBoundary}>Try again</button>\n    </div>\n  );\n}\n')),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"resetErrorBoundary")," function is called when the ",(0,t.yg)("inlineCode",{parentName:"p"},"retry")," button is clicked. This will reset the error boundary and retry the render.\nYou see that the library has made it easy for us to handle errors in our React application. We don't need to create an Error Boundary component, the library has done that for us. We only need to use it in our React application."),(0,t.yg)("h2",{id:"fallbackcomponent-prop"},"FallbackComponent prop"),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"react-error-boundary")," library also provides us with a ",(0,t.yg)("inlineCode",{parentName:"p"},"FallbackComponent")," prop. This prop is used to render a fallback UI when an error occurs. It is a React component."),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-tsx"},'function ErrorFallbackComponent({ error, resetErrorBoundary }) {\n  return (\n    <div role="alert">\n      <p>Something went wrong:</p>\n      <pre style={{ color: "red" }}>{error.message}</pre>\n      <button onClick={resetErrorBoundary}>Try again</button>\n    </div>\n  );\n}\n\n<ErrorBoundary FallbackComponent={ErrorFallbackComponent}>\n  <ExampleApplication />\n</ErrorBoundary>;\n')),(0,t.yg)("p",null,"The ",(0,t.yg)("inlineCode",{parentName:"p"},"ErrorFallbackComponent")," is a React component that renders a fallback UI when an error occurs. It receives two props: ",(0,t.yg)("inlineCode",{parentName:"p"},"error")," and ",(0,t.yg)("inlineCode",{parentName:"p"},"resetErrorBoundary"),". The ",(0,t.yg)("inlineCode",{parentName:"p"},"error")," is the error message details and the ",(0,t.yg)("inlineCode",{parentName:"p"},"resetErrorBoundary")," is a function that can be called to reset the error boundary and retry the render."),(0,t.yg)("h2",{id:"bonus-best-practices-for-error-boundaries"},"Bonus: Best Practices for Error Boundaries"),(0,t.yg)("p",null,"When using error boundaries in React, there are a few good practices to follow that ensure the error boundaries work well and do not break the performance or user experience."),(0,t.yg)("h4",{id:"use-error-boundaries-strategically"},"Use Error Boundaries Strategically"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"Avoid wrapping your ",(0,t.yg)("strong",{parentName:"li"},"entire application")," in a single error boundary. This might sound like a good idea for global error handling, but it can lead to a poor user experience. Instead, wrap smaller sections of the component tree.\nFor instance, wrapping error boundaries around the sidebar, dashboard, or form ensures that only the feature that throws the error will show the fallback UI, while the rest of the application continues to work.")),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-jsx"},"<ErrorBoundary>\n  <Header />\n  <ErrorBoundary>\n    <MainContent />\n  </ErrorBoundary>\n  <Footer />\n</ErrorBoundary>\n")),(0,t.yg)("h4",{id:"pick-the-right-fallback-ui"},"Pick the Right Fallback UI"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},'Make a user-friendly, informative fallback UI. Avoid generic messages like "Something went wrong." Provide clearer descriptions or actions users can take, such as reloading the page or contacting support.'),(0,t.yg)("li",{parentName:"ul"}
1,"Customize the fallback UI depending on where the error occurs. For example, if an error happens in a form, show a form-specific error message with a retry option.")),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-jsx"},"if (this.state.hasError) {\n  return <h1>Oops! Something went wrong. Please try again later.</h1>;\n}\n")),(0,t.yg)("h4",{id:"granularity-matters"},"Granularity Matters"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"Find the right balance in how many error boundaries you use. Wrapping too many small components adds unnecessary complexity, while too few error boundaries could break large sections of your app if an error occurs.\nBest practice: wrap error boundaries around ",(0,t.yg)("strong",{parentName:"li"},"independent features")," or sections that can fail without breaking the whole app (e.g., third-party components, dynamic content areas, or data fetching components).")),(0,t.yg)("h4",{id:"logging-and-monitoring"},"Logging and Monitoring"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"Error boundaries should be more than just UI fallbacks. Use the ",(0,t.yg)("inlineCode",{parentName:"li"},"componentDidCatch")," lifecycle method to log errors to an external service like Sentry, Datadog, or a custom logging system."),(0,t.yg)("li",{parentName:"ul"},"Logging helps track issues that may not be visible to the user but still need to be fixed, especially in production environments.")),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-jsx"},"componentDidCatch(error, info) {\n  logErrorToService(error, info); // Log error and stack trace\n}\n")),(0,t.yg)("h4",{id:"consider-using-libraries-for-error-boundaries"},"Consider Using Libraries for Error Boundaries"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"You can use libraries like ",(0,t.yg)("inlineCode",{parentName:"li"},"react-error-boundary"),", which offer features like automatic retries, reset functionality, and better support for functional components."),(0,t.yg)("li",{parentName:"ul"},"This saves time and ensures best practices are followed.")),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-jsx"},"<ErrorBoundary FallbackComponent={ErrorFallback} onReset={() => resetApp()}>\n  <MyComponent />\n</ErrorBoundary>\n")),(0,t.yg)("h4",{id:"testing-your-error-boundaries"},"Testing Your Error Boundaries"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"Test your error boundaries to ensure they display the correct fallback UI and log errors. You can use libraries like Jest or React Testing Library to simulate component failures and validate error handling logic."),(0,t.yg)("li",{parentName:"ul"},"Mock errors in child components and check if the fallback UI renders as expected.")),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-jsx"},'it("renders fallback UI on error", () => {\n  const { getByText } = render(\n    <ErrorBoundary>\n      <BrokenComponent />\n    </ErrorBoundary>,\n  );\n  expect(getByText("Something went wrong")).toBeInTheDocument();\n});\n')),(0,t.yg)("h4",{id:"error-boundaries-for-third-party-components"},"Error Boundaries for Third-Party Components"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"If you're using third-party components or libraries, add error boundaries around them so bugs in those components won't break your whole app.")),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-jsx"},"<ErrorBoundary fallback={<h2>Failed to load chart</h2>}>\n  <ChartComponent />\n</ErrorBoundary>\n")),(0,t.yg)("h4",{id:"avoid-overuse"},"Avoid Overuse"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},"Don\u2019t overuse error boundaries. They are not a substitute for good code practices like proper error handling in event handlers, API calls, and promises. Error boundaries should be the last line of defense, not the primary error management tool.")),(0,t.yg)("h4",{id:"reset-state-on-error"},"Reset State On Error"),(0,t.yg)("ul",null,(0,t.yg)("li",{parentName:"ul"},'Sometimes you may want to reset your app\'s state after an error, like when a user clicks "Try Again." You can reset the error boundary\u2019s state and re-render the component.'),(0,t.yg)("li",{parentName:"ul"},"Libraries like ",(0,t.yg)("inlineCode",{parentName:"li"},"react-error-boundary")," handle this with ",(0,t.yg)("inlineCode",{parentName:"li"},"resetErrorBoundary"),".")),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-jsx"},"const FallbackComponent = ({ error, resetErrorBoundary }) => (\n  <div>\n    <p>Something went wrong!</p>\n    <button onClick={resetErrorBoundary}>Try Again</button>\n  </div>\n);\n")),(0,t.yg)("h2",{id:"dealing-with-errors-in-asynchronous-operations-in-react"},"Dealing with Errors in Asynchronous Operations in React","*","*"),(0,t.yg)("p",null,"I would like to share some quick thoughts on how we 
1could manage errors with asynchronous operations since React Error Boundaries don't catch them. For example, if an API call or Promise fails, the error wouldn't be caught by the error boundary."),(0,t.yg)("p",null,"To manage this, we can either use the ",(0,t.yg)("inlineCode",{parentName:"p"},".catch()")," method with Promises or try-catch blocks with async functions. Here's a simple example for fetching data:"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-js"},'fetchData()\n  .then((response) => setData(response))\n  .catch((error) => {\n    console.error("Error fetching data:", error);\n    setError(true); // We can show an error message in the UI\n  });\n')),(0,t.yg)("p",null,"For async/await, we can use ",(0,t.yg)("inlineCode",{parentName:"p"},"try...catch"),":"),(0,t.yg)("pre",null,(0,t.yg)("code",{parentName:"pre",className:"language-js"},'async function fetchData() {\n  try {\n    const response = await fetch(url);\n    setData(response);\n  } catch (error) {\n    console.error("Error fetching data:", error);\n    setError(true);\n  }\n}\n')),(0,t.yg)("p",null,"This way, if something goes wrong with our API request, we can display a fallback UI, log the error, and prevent the whole component from breaking."))}h.isMDXComponent=!0}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.