Error Boundaries in React v16.0
React v16 is out and so it is the new talk of the town. And yes React has migrated to MIT license.
React v16 has come up with some new features and Error Boundaries is one of them. So, this article is all about Error Boundaries like what are they, how to use them and things like that.
In react, any runtime error during rendering puts React in a broken state and the whole component tree is unmounted from the root and needs a refresh to recover.
This can be prevented using a special React component called Error Boundaries which provides a fallback UI in case of a runtime error, like try-catch block.
These components are implemented using a special lifecycle method which catches any error in their child component tree. React v15 had this method with name unstable_handleError, but had very limited support for error boundaries. This unstable_handleError method no longer works as React v16 provided a new method called componentDidCatch.
Error boundaries catch errors of child components only. Any error within itself will not be caught and the error will propagate the closet Error Boundary above it. And any error not caught by any Error Boundary will propagate to the root and crash/uproot the whole app. Please see the pen and gist below.
There was a discussion within the React team whether it’s a good idea to keep a corrupted UI than completely remove it. But they have used it in there products. For example, Facebook Messenger wraps content of the sidebar, the info panel, the conversation log, and the message input into separate error boundaries. If some component in one of these UI areas crashes, the rest of them remain interactive.
It’s totally upto your product’s design.
React team also encourages to use JS error reporting services so that one can learn about unhandled exceptions as they happen in production, and fix them.
You can also see filenames and line numbers in component stack using babel plugin babel-plugin-transform-react-jsx-source.
If one is using unstable_handleError from React v15 and want to migrate to React v16, the React team has provided a codemod.
Error Handling in React v16 by Dan Abramov
I’m currently working on some cool stuff with React at Raja Software Labs, Pune. You can reach me on twitter.
If you liked the article, please hit the clap icon.