Error Boundaries - Overview


  • JavaScript errors within Components can corrupt an entire App
  • Boundaries place a container around errors to prevent propagation
  • Child components errors are caught and contained
  • Fallback UI can be rendered on error


  • Only catch errors below themselves in the Render tree
  • Cannot catch
    • Errors in Event handlers
    • Asyncronous code such as setTimeout or requestAnimationFrame
    • React pages generated on the Server
    • Errors from the ErrorBoundary itself

Error Boundaries - Creation

  • Any component can be a boundary if defines componentDidCatch
  • componentDidCatch behaves like JavaScript catch {}
  • Only React Class components can be Boundaries
class ErrorBoundary extends React.Component {
  constructor(props) {
    this.state = { hasError: false };

  componentDidCatch(error, info) {
    // Display fallback UI
    this.setState({ hasError: true });
    // You can also log the error to an error reporting service
    logErrorToMyService(error, info);

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    return this.props.children;
  <MyWidget />

Error Boundaries - componentDidCatch

  • error is a JavaScript error object
  • info is a JavaScript object with componentStack
    • Holds information about the component stack at the time of error
  • Can be used as a top level wrapper, or many small error wrappers
componentDidCatch(error, info) {

  /* Example stack information:
     in ComponentThatThrows (created by App)
     in ErrorBoundary (created by App)
     in div (created by App)
     in App


Error Boundaries - Within Event Handlers

  • Event handlers are just normal JavaScript
  • Use regular try/catch syntax
function MyComponent (props) {

  const [error, setError] = useState(null)

  const handleClick = () => {
    try {
      // Do something that could fail
    } catch (error) {

  if (error) {
    return <h1>Caught an error.</h1>
  return <div onClick={this.handleClick}>Click Me</div>

Error Boundaries - Live Example

See the Pen oMRpQg by Joshua Burke (@Dangeranger) on CodePen.

Error Boundaries - Stack Traces


With Create-React-App