Description
React 16 introduced a pattern of utilizing ErrorBoundary components to handle UI errors that might otherwise break the application. I touched on this idea in this post and think it might be a decent candidate for the cookbook. I could reuse a lot of the examples within the post.
A rough outline:
Base Example
Create a simple component which throws an error during render. Introduce errorCaptured
hook and show how the hook will capture the error for us. Extract the errorCaptured
into its own component that wraps any other components and show how it still captures the errors and can render a different UI when an error occurs.
Details about the Value
Go into more detail about the errorCaptured
hook (parameters, error propagation). Details about why its a compelling pattern may include separation of error handling and UI display, code reuse, component composition vs. imperative code, granularity (individual widget vs. application error handling).
Real-World Example
Start off by rebuilding a more robust ErrorBoundary component that can take other components as props for fall back UIs, callback functions and emits error events. Example could be similar to the one in my article where v-for
over list results in an error and how we can use our new ErrorBoundary to remedy the situation.
When To Avoid This Pattern
The ErrorBoundary component will not work if it directly wraps functional components. There are also only a few places the errorCaptured
hook will catch errors.
Alternative Patterns
Since the ErrorBoundary component acts like try/catch
we can use one in its place, especially in areas where the ErrorBoundary will not work.
Let me know if you think this would be a good candidate or not! Thanks!