Last active
May 26, 2020 14:27
-
-
Save SahanAmarsha/f2717864502bdb07aa2109eba352dbd2 to your computer and use it in GitHub Desktop.
How to lazy load components in your React App
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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