Problem

Work is done in the rendering method.

What happens when something breaks in the rendering?

 

Solution

Use Error Boundaries

 

The problem

function Blah({user}) {
  if (!user) {
     throw new Error("No bloody user")
  }

  return <h1>{user.name}</h1>
}




<Blah />. // Boom an error makes React crash

 

// An example of using an Error Boundary

import {ErrorBoundary} from 'react-error-boundary'

function Fallback({ error }) {

  return (
    <div role="alert">
      <p> No user provided: </p>

      <pre>{error.message}</pre>

    </div>
  )
}





<ErrorBoundary FallbackComponent={Falback} >

   <App />

</ErrorBoundary>