I am trying to implement some code splitting in a React application. This isn't strictly necessary in this case as it's a rather small application, but I thought I would try this technique out in a low risk setting before implementing it in larger projects.
My code that works:
import React from 'react'
import { useUser } from './context/userContext'
import Layout from './components/layout'
import Routes from './components/routes'
import LandingScreen from './components/authApp/LandingScreen'
const App = () => {
const user = useUser()
return (
<>
{user ? (
<Layout>
<Routes />
</Layout>
) : (
<LandingScreen />
)}
</>
)
}
export default App
If I try to change any components to use React.lazy, for instance
const LandingScreen = React.lazy(() => import('./components/authApp/landingScreen'))
My app compiles fine, but no components render in the browser, and I receive this error:
index.js:1 The above error occurred in one of your React components:
in Unknown (at App.js:26)
in App (at src/index.js:14)
in UserProvider (at appProvider.js:7)
in AuthProvider (at appProvider.js:6)
in AppProviders (at src/index.js:13)
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/docs/error-boundaries.html to learn more about error boundaries.
I'd appreciate any clues to what I'm doing wrong here. The LandingScreen component just renders some divs and my login component, but the same error occurs even if it is just rendering a single div.'
Edit: Wrapping the lazy loaded component in a Suspense component fixes it. The docs seem to indicate that the Suspense component is optional, but maybe it's not? Anyone that knows more and can chime in, that would be appreciated.
Suspensecomponent or an alternative,". If you have ideas for a clearer way to describe this I'm open to the conversation.