Skip to main content
InterviewHubPRO
Section Overview
Q382

Question 382 of 407

Part 9: React Hooks Deep Dive (262 - 316)

94%
React Core & Hooks (407 Qs)•Part 9: React Hooks Deep Dive (262 - 316)

What is the purpose of getDerivedStateFromError?

junior LevelCode ExampleHooks

This lifecycle method is invoked after an error has been thrown by a descendant component. It receives the error that was thrown as a parameter and should return a value to update state.

csharp
The signature of the lifecycle method is as follows,
javascript
    static getDerivedStateFromError(error)
vbnet
Let us take error boundary use case with the above lifecycle method for demonstration purpose,
javascript
    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.
        return { hasError: true };
      }

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

        return this.props.children;
      }
    }