3

I am trying to learn how to use Error Boundaries in React js.As i read here it prevent your application from getting crashed. But my application crash!here is my code:

App component:

function App() {
  return (
    <>
      <h1>app component</h1>
      <ErrorBoundary >
        <Simple />
      </ErrorBoundary>
    </>
  );
}

Simple Component:

export default () => {
    throw new Error('I crashed!')
    return <h3> simple component</h3>
}

and this my Boundaries=

class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props);
        this.state = { hasError: false };
    }

    static getDerivedStateFromError(error) {
        // Update state so the next render will show the fallback UI.
        console.log("I got you ")
        return { hasError: true };

    }

    componentDidCatch(error, errorInfo) {
        // You can also log the error to an error reporting service
        console.log(error, errorInfo);


    }

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

        return this.props.children;
    }
}
export default ErrorBoundary;

for a very short time I see the message "Something went wrong" but after that the page crashed!

thanks for your help and advice

2 Answers 2

7

If the application is crashing in the development environment, it is expected behavior so that a developer can fix the issue.

ErrorBoundaries are supposed to work without crashes only in the production environment.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Nikhili you are right I have just tried it in production mode and it works!! I am wondering why the document didn't mention it!
Why? I don't understand the logic in this. I mean, of course a dev should fix it. But a dev can easily fix it even if the error boundary works, you'll still get the error. So why break the application? It just makes it harder to test.
1

Your code is correct and stable. See demo

The only thing you forgotten is closing tag for <h3> in Simple Component.

export default () => {
    throw new Error('I crashed!')
    return <h3> simple component</h3>
}

And Error boundaries work in development.

1 Comment

Hi Fyodor simple code is something i write just here. and I think it doesn't matter because codes after the throw error are not executed. also my entire sample code works fine when the throw error line is commented. and I think your right about error boundary behavior in development mode there is nothing in document that mentioned it just work in production.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.