Skip to content

Instantly share code, notes, and snippets.

@SahanAmarsha
Last active May 26, 2020 14:27
Show Gist options
  • Save SahanAmarsha/f2717864502bdb07aa2109eba352dbd2 to your computer and use it in GitHub Desktop.
Save SahanAmarsha/f2717864502bdb07aa2109eba352dbd2 to your computer and use it in GitHub Desktop.
How to lazy load components in your React App
//importing lazy and suspense from react library
import React,{lazy, Suspense} from 'react';
//lazy loading the requied components
const Home = React.lazy(() => import('./modules/pages/Home'));
const Profile = React.lazy(() => import('./modules/pages/Profile'));
const About = React.lazy(() => import('./modules/pages/About'));
//wrapping your switch compoent (inside react-router) with <Suspense>
<Router>
<main>
<Suspense> //*NEW*
<Switch>
<Route path="/" exact>
<Home />
</Route>
<Route path="/profile" exact>
<Profile />
</Route>
<Route path="/about">
<About />
</Route>
</Switch>
</Suspense> //*NEW*
</main>
</Router>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment