I recently added Suspense, a feature of React, to one of my projects. I learnt the following;
- It's awesome and works effortlessly
- You need error boundaries
- It works great with react-router but you do need to mind how you configure it
- Error boundaries will make the sub-routes inaccessible when an error is thrown. Instead of wrapping multiple routes, it's better to wrap components on a route-by-route basis instead
- If you do use an error boundary component as a child of a router <Switch /> component, you may find that the switch's behaviour no longer works as expected
So how do I use it all exactly? Well, that's easy, I created my own little higher-order component. Florals? For spring? Groundbreaking.
In place of a regular <Route />
component, I use this this <SuspenseRoute />
. Pass all the usual props along and they get handed down with some extra magic thrown into the mix!
const SuspenseRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={route => ( <ErrorBoundary> <Suspense fallback={<SuspenseLoading />}> <Component {...route} /> </Suspense> </ErrorBoundary> )} /> );