Learn React Error Boundaries In 7 Minutes

Web Dev Simplified · Beginner ·🖊️ Copywriting & Content Strategy ·3y ago

Key Takeaways

The video demonstrates how to use React error boundaries to catch and handle errors in React applications, utilizing the getDerivedStateFromError and componentDidCatch methods to update state and log errors.

Full Transcript

one of the biggest things that separates a junior developer from a more advanced developer is how they handle errors most Junior developers don't even think about errors and don't do any error handling at all and if you do that in react your application is going to look something like this as you can see as soon as you run into your very first error the entire application goes entirely blank and that is obviously a terrible user experience so in this video I'm going to show you how easy it is to do error handling in react with error boundaries welcome back to web dev simplified my name is Kyle and my job is to simplify the web for you so you can start building your dream project sooner for this video we have a really simple application if I refresh my page on the right you see we have some loading text and we're just loading in some information asynchronously in our application as you can see really super straightforward what's happening and if we look at the code for it it's also relatively straightforward we just have some data components that are rendering different types of data based on the type that I pass in and inside this component it's using this brand new use hook inside of react to get that data asynchronously if you're not familiar with the use hook I have an entire video covering I'll link in the cards in description and I even have a completely free react hook simplified course that covers every hook in react I'll link that down in the description as well for you but essentially what this does is it gets some data asynchronously for us and I also added in the ability to simulate what happens in the case of an error so if we come in here we can add that to any of these we can just say has error and that's going to simulate what happens if we throw an error from our request because it's a bad request and now when I save you can see we're going to get an error and the entire application goes completely blank and if I inspect and I look at my console you can see we obviously have errors inside of here which is not great now you already know that there are lots of different ways that I could handle this type of error for example if I'm making a fetch request I could just do a catch on my promise to catch the error that way or I could do that with any promise really but a fetch request is kind of the most logical thing you think of and you can handle the error directly inside the component where you're making that request but sometimes that's not always the best route because now you have error logic and loading logic and all that inside your component which really muddies things up a little bit which is where error boundaries come in they're really great for catching Errors By catching them inside your component without actually being part of your component because they live outside of your component now I know that sounds kind of confusing but let me show you exactly what an error boundary is I actually have one written up here for you so you don't have to watch me type it but essentially an error boundary is just a component that you create inside of react so here's a really simple example of one you'll notice that this is actually a class component and that's because to create an error boundary it must be a class component CU you need to take advantage of this method right here that's built into a class component so before I dive into exactly what this code is doing let me explain the purpose of an error boundary an error boundary has this method right here called get derive state from error and anytime this component or any components that are children of this component throw an error what's going to happen is instead of you know completely wiping out your application as you can see on the right here what's going to happen is it's going to call this method right here and it's going to allow you to update the state of this component based on the error that happened in our case we're not even using the error all we're doing is we're just moving around a toggle that says do we have an error or not that's the only thing in the state for this component we're just saying has there been an error or not if this function right here gets called that means that somewhere in our application whether it's this component or any of the children of this component there was an error so we set this to true and then in our component the only thing we care about is this props for fallback we're just passing a fallback component along with it so we can say if there's an error render out this fallback data otherwise render out the children let me show you how this looks when we actually want to use this let's say I come inside of here and this is the component that I'm having the problems with so I'm just going to wrap it inside my error boundary so I can say error boundary just like that wrap my entire component inside of that and I need to make sure that I import this error boundary so we can just say import error boundary from and I want to get it fromer boundary just like that so I give this a quick save and I refresh my page over here you're going to see that now it's rendering out the text error and that's because what's happening is inside my data component I have an error being thrown and my error boundary is actually wrapping that data component so what's happening is in my error boundary if we open that back up here this it derived state from error is being called with our error and we're saying hey there has been an error so that's set to true now our component rerenders cuz the state has changed it says that if we've had an error is true then it renders this fallback otherwise we're just normally rendering the children so by default this component does nothing because all it does is render out the children until an error happens in your application and then what's going to happen is it's going to render whatever fallback you pass to that actual component this is why it's really important that you wrap specific sections of your application and error boundaries for example each one of these cards I should wrap inside of its own error boundary let me just do that real quick there we go so now no matter what happens if any of these fail I'm just going to get the text error instead of something else bad happening like my application going entirely blank another really good use case for an error boundary is actually to wrap your entire application here where we have our app it makes a lot of sense to wrap the entire thing inside of this error boundary let me just make sure I import that and I close it off and then you can put something inside of here like there was an error and now no matter what happens in your application the user will be notified because you're saying hey there's been some type of error let the user know so if I remove these other error boundaries for example here and now we have that error that occurs you're going to see it's going to fall back to that main error boundary that I have wrapping my entire application and I almost always recommend wrapping your entire application in some type of error boundary just to make sure that people know that there has been an error so that's kind of the main use cases for the error boundary so I want go back into the arrow boundry to really talk about exactly what's going on inside of here to go a little bit further so we already know that this function right here gets called anytime your component in the children has an error and another method that automatically gets called is this component did catch this will also get called every single time that there's an error the same way that this function right here gets called but the main difference is while this is for updating your state as the name implies this function is actually for running specific code in most cases this is going to be like sending off a log to your server or making some type of log in your database right right now we're just logging out this information to the console and if we inspect the page and we look at the console you can see that it's printing out here the error message that we're getting as well as an object that contains the entire stack trace for where that eror came from so we can see the component stack so we can see what components actually cause this error to happen so the combination of these two different functions is really crucial because this first function allows you to render out some fallback data most often when you create an error boundary you're just going to give it a simple true false State and then you're going to pass in a prop for the fallback you can viously make this component as complex or simple as you want this is probably one of the more simple use cases but 99% of the time that's really all you need then this second function right here is really useful for any logging or reporting systems that you have you can actually make sure you log those errors to your reporting system and then you can go check those and you can see exactly what's happening in your application you'll have the component stack you'll have the error it'll give you all the information you need and that's all there is to error boundaries in react if you want to learn more about that used hook or any other react hook I highly recommend checking out my completely free react hook simplified course it'll be linked down in the description for you with that said thank you very much for watching and have a good day

Original Description

FREE React Hooks Simplified Course: https://courses.webdevsimplified.com/react-hooks-simplified Handling errors is something that most junior developers completely overlook, but it is one of the most important things you can do in any React application. In this video I will show you how to use ErrorBoundaries in React to handle and catch errors properly. 📚 Materials/References: FREE React Hooks Simplified Course: https://courses.webdevsimplified.com/react-hooks-simplified useHook Video: https://youtu.be/zdNF9FJWJ8o 🌎 Find Me Here: My Blog: https://blog.webdevsimplified.com My Courses: https://courses.webdevsimplified.com Patreon: https://www.patreon.com/WebDevSimplified Twitter: https://twitter.com/DevSimplified Discord: https://discord.gg/7StTjnR GitHub: https://github.com/WebDevSimplified CodePen: https://codepen.io/WebDevSimplified ⏱️ Timestamps: 00:00 - Introduction 00:36 - Project Demo 01:59 - Error Boundary Basics 05:27 - Error Boundary componentDidCatch #ErrorBoundary #WDS #ReactJS
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Web Dev Simplified · Web Dev Simplified · 0 of 60

← Previous Next →
1 Introduction to Web Development || Setup || Part 1
Introduction to Web Development || Setup || Part 1
Web Dev Simplified
2 Introduction to Web Development || Understanding the Web || Part 2
Introduction to Web Development || Understanding the Web || Part 2
Web Dev Simplified
3 Introduction to HTML || Your First Web Page || Part 1
Introduction to HTML || Your First Web Page || Part 1
Web Dev Simplified
4 Introduction to HTML || Basic HTML Elements || Part 2
Introduction to HTML || Basic HTML Elements || Part 2
Web Dev Simplified
5 Introduction to HTML || Advanced HTML Elements || Part 3
Introduction to HTML || Advanced HTML Elements || Part 3
Web Dev Simplified
6 Introduction to HTML || Links and Inputs || Part 4
Introduction to HTML || Links and Inputs || Part 4
Web Dev Simplified
7 Learn Git in 20 Minutes
Learn Git in 20 Minutes
Web Dev Simplified
8 5 Must Know Sites For Web Developers
5 Must Know Sites For Web Developers
Web Dev Simplified
9 10 Best Visual Studio Code Extensions
10 Best Visual Studio Code Extensions
Web Dev Simplified
10 Learn CSS in 20 Minutes
Learn CSS in 20 Minutes
Web Dev Simplified
11 How to Style a Modern Website (Part One)
How to Style a Modern Website (Part One)
Web Dev Simplified
12 How to Style a Modern Website (Part Two)
How to Style a Modern Website (Part Two)
Web Dev Simplified
13 3D Flip Button Tutorial
3D Flip Button Tutorial
Web Dev Simplified
14 How to Style a Modern Website (Part Three)
How to Style a Modern Website (Part Three)
Web Dev Simplified
15 Animated Loading Spinner Tutorial
Animated Loading Spinner Tutorial
Web Dev Simplified
16 How to Write the Perfect Developer Resume
How to Write the Perfect Developer Resume
Web Dev Simplified
17 Animated Text Reveal Tutorial
Animated Text Reveal Tutorial
Web Dev Simplified
18 Learn Flexbox in 15 Minutes
Learn Flexbox in 15 Minutes
Web Dev Simplified
19 Custom Checkbox Tutorial
Custom Checkbox Tutorial
Web Dev Simplified
20 Start Contributing to Open Source (Hacktoberfest)
Start Contributing to Open Source (Hacktoberfest)
Web Dev Simplified
21 JavaScript Shopping Cart Tutorial for Beginners
JavaScript Shopping Cart Tutorial for Beginners
Web Dev Simplified
22 Responsive Video Background Tutorial
Responsive Video Background Tutorial
Web Dev Simplified
23 1,000 Subscriber Giveaway
1,000 Subscriber Giveaway
Web Dev Simplified
24 How To Prevent The Most Common Cross Site Scripting Attack
How To Prevent The Most Common Cross Site Scripting Attack
Web Dev Simplified
25 Transparent Login Form Tutorial
Transparent Login Form Tutorial
Web Dev Simplified
26 The Forgotten CSS Position
The Forgotten CSS Position
Web Dev Simplified
27 How to Code a Card Matching Game
How to Code a Card Matching Game
Web Dev Simplified
28 10 Must Install Visual Studio Code Extensions
10 Must Install Visual Studio Code Extensions
Web Dev Simplified
29 Learn CSS Grid in 20 Minutes
Learn CSS Grid in 20 Minutes
Web Dev Simplified
30 Learn JSON in 10 Minutes
Learn JSON in 10 Minutes
Web Dev Simplified
31 10 Essential Keyboard Shortcuts For Programmers
10 Essential Keyboard Shortcuts For Programmers
Web Dev Simplified
32 What Is The Fastest Way To Load JavaScript
What Is The Fastest Way To Load JavaScript
Web Dev Simplified
33 Differences Between Var, Let, and Const
Differences Between Var, Let, and Const
Web Dev Simplified
34 How To Install MySQL (Server and Workbench)
How To Install MySQL (Server and Workbench)
Web Dev Simplified
35 Learn SQL In 60 Minutes
Learn SQL In 60 Minutes
Web Dev Simplified
36 How To Solve SQL Problems
How To Solve SQL Problems
Web Dev Simplified
37 What Are Design Patterns?
What Are Design Patterns?
Web Dev Simplified
38 Null Object Pattern - Design Patterns
Null Object Pattern - Design Patterns
Web Dev Simplified
39 Your First Node.js Web Server
Your First Node.js Web Server
Web Dev Simplified
40 How To Setup Payments With Node.js And Stripe
How To Setup Payments With Node.js And Stripe
Web Dev Simplified
41 How To Learn Any New Programming Skill Fast
How To Learn Any New Programming Skill Fast
Web Dev Simplified
42 Asynchronous Vs Synchronous Programming
Asynchronous Vs Synchronous Programming
Web Dev Simplified
43 JavaScript ES6 Arrow Functions Tutorial
JavaScript ES6 Arrow Functions Tutorial
Web Dev Simplified
44 Are You Too Old To Learn Programming?
Are You Too Old To Learn Programming?
Web Dev Simplified
45 JavaScript Cookies vs Local Storage vs Session Storage
JavaScript Cookies vs Local Storage vs Session Storage
Web Dev Simplified
46 JavaScript Promises In 10 Minutes
JavaScript Promises In 10 Minutes
Web Dev Simplified
47 Builder Pattern - Design Patterns
Builder Pattern - Design Patterns
Web Dev Simplified
48 JavaScript == VS ===
JavaScript == VS ===
Web Dev Simplified
49 JavaScript ES6 Modules
JavaScript ES6 Modules
Web Dev Simplified
50 8 Must Know JavaScript Array Methods
8 Must Know JavaScript Array Methods
Web Dev Simplified
51 CSS Variables Tutorial
CSS Variables Tutorial
Web Dev Simplified
52 JavaScript Async Await
JavaScript Async Await
Web Dev Simplified
53 How To Choose Your First Programming Language
How To Choose Your First Programming Language
Web Dev Simplified
54 Easiest Way To Work With Web Fonts
Easiest Way To Work With Web Fonts
Web Dev Simplified
55 Singleton Pattern - Design Patterns
Singleton Pattern - Design Patterns
Web Dev Simplified
56 Responsive Navbar Tutorial
Responsive Navbar Tutorial
Web Dev Simplified
57 CSS Progress Bar Tutorial
CSS Progress Bar Tutorial
Web Dev Simplified
58 Learn GraphQL In 40 Minutes
Learn GraphQL In 40 Minutes
Web Dev Simplified
59 What is an API?
What is an API?
Web Dev Simplified
60 Learn How To Build A Website In 1 Hour!
Learn How To Build A Website In 1 Hour!
Web Dev Simplified

This video teaches how to use React error boundaries to catch and handle errors in React applications, making it a crucial skill for any React developer. By learning how to implement error boundaries, developers can improve the reliability and user experience of their applications. The video provides a step-by-step guide on how to create error boundaries and use the getDerivedStateFromError and componentDidCatch methods.

Key Takeaways
  1. Create an error boundary component
  2. Use the getDerivedStateFromError method to update the state based on the error that occurred
  3. Wrap a component in an error boundary to catch and display errors
  4. Use the componentDidCatch lifecycle method to catch errors in a component
  5. Display a fallback component when an error occurs
💡 The combination of getDerivedStateFromError and componentDidCatch methods is crucial for effective error handling in React applications.

Related Reads

Chapters (4)

Introduction
0:36 Project Demo
1:59 Error Boundary Basics
5:27 Error Boundary componentDidCatch
Up next
Clearly state who you help
Merit Marketing Services
Watch →