AI Hints
Home›React Tutorial›Errors and Portals
React · Lesson 73 of 120

Error Boundaries

Catch crashes.

⏱ 2 min read▶ Video at 1:00:55🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

If a component throws an error while rendering, React removes the whole page. An error boundary catches the error, and shows a fallback for just that part.

  • One error
  • Whole page gone
  • Catch it

Catching a broken widget

An error boundary catches errors thrown while rendering its children. It's still written as a class, one of the few places classes remain. Get derived state from error stores the error, and render shows a fallback. The rest of the page keeps working. We break the reviews. Run it.

App.jsxjsx
import { Component, useState } from "react";
class ErrorBoundary extends Component {
  state = { error: null };
  static getDerivedStateFromError(error) { return { error }; }
  render() {
    if (this.state.error) return <p className="box">Sorry, reviews are unavailable.</p>;
    return this.props.children;
  }
}
function Reviews({ broken }) {
  if (broken) throw new Error("Reviews failed to load");
  return <p>★★★★★ from 212 riders</p>;
}
export default function App() {
  const [broken, setBroken] = useState(false);
  return (<div><h2>Trail 500</h2>
    <ErrorBoundary><Reviews broken={broken} /></ErrorBoundary>
    <button id="break" onClick={() => setBroken(true)}>Break reviews</button></div>);
}
Output
Error: Reviews failed to load
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}
Also uses actions.json
[{"click": "#break"}]

In practice

Most teams use the small react error boundary package, so they don't write the class themselves. Boundaries catch render errors, not errors in event handlers or async code. Handle those with try and catch.

keyvalue
Packagereact-error-boundary
Catchesrender errors
Notevent handlers
Usetry / catch there

Summary

Wrap risky parts of the page in an error boundary, so one crash doesn't take everything down. Next, portals.

Key takeaways
  • Error boundary
  • Fallback
  • Rest keeps working
Next up: Portals — modals