reactjstry-catchreact-error-boundary

error boundary component catches error but disappears straight away


I have a component that is deliberately throwing an error, wrapped in an error boundary component.

It catches the error and displays the message but only for a split second.

This is my wrapped component

  useEffect(() => {   
        error(); 
    }, []);

    const error = () => {
        try {
            return [].replace(/'--'/, '')
        } catch (error) {
           throw(error)
            
        }
    }

and my error boundary component

class ErrorBoundary extends Component {
    constructor(props) {
      super(props);
      this.state = { hasError: false };
    }
  
    static getDerivedStateFromError(error) {
        console.log('derived', error)
      // Update state so the next render will show the fallback UI.
      return { hasError: true };
    }
  
    componentDidCatch(error, errorInfo) {
        console.log('error did catch', error)
      this.setState({ hasError: true})
    }
  
    render() {
      if (this.state.hasError) {
        return (
            <h1>Something went wrong.</h1>
        );
      }
  
      return this.props.children; 
    }
  }

Then i am declaring the components like so

<ErrorBoundary>
   <ProfileContainer />
</ErrorBoundary>

When my component loads it catches the error as it should and it's receiving it in the boundary component. It displays the error message but then immediately crashes

enter image description here

Am I handling this the wrong way? I know error boundaries are for DOM errors but its interesting that it is catching the error.

Any help greatly appreciated


Solution

  • This is intentional. Error boundaries are primarily useful for production, but in development, react wants to make errors as highly visible as possible (so the stack trace appears no matter what).

    In production mode, your site will show only the error boundary UI.