Debugging React Apps
Logical Errors and Source Maps
When React builds your code for the browser, it's bundled and very different from your src
files. However, your browser is often given access to a source map, which allows it to reverse engineer back to the src
files. You can then interact with the code to spot your logical errors.
Note: You can access the src
files in Sources in Chrome and Debugger in Firefox.
How to use Sources or Debugger to debug logical errors:
Read through your code and hypothesize which line of code your logic starts to go wrong.
In Sources/Debugger, add a breakpoint by clicking on the line number.
Interact with the app to trigger that line of code. The code will pause at that breakpoint.
When you hover over each variable name, the browser will tell you the value. This is how you check for logical errors!
Error Boundaries
As of React 16+, you can create custom error messages if a component fails to render that replaces the component. These are called error boundaries.
Pro tip: Error boundaries are useful when you can't avoid the potential for an error, but you don't want the error to break the entire app. Instead, you want a custom alternative component to render.
Here's the general structure of an ErrorBoundary
component:
Using ErrorBoundary
, you then wrap it around the component you care about conditionally rendering:
Now if Component
runs into an error, ErrorBoundary
will instead render a custom error-related component.
How it works: ErrorBoundary
listens for when its child components break. When that happens, it simply invokes componentDidCatch
.
Last updated