React.Suspense and React.Lazy for Lazy Loading Components — ReactJS optimization technique
Lazy loading is a great technique for speeding and optimizing up the render time of your React app. The basic idea of lazy loading is to load a component only when it is needed.
React comes bundled with the React.lazy API so that you can render a dynamic import as a regular component.
So instead of loading your regular component like this:
import OtherComponent from ‘./OtherComponent’;
You can boost your app’s performance by using the lazy method to render a component like this:
const OtherComponent = React.lazy(() => import(‘./OtherComponent’));
React.lazy takes a function that must call a dynamic “import”. It will then return a Promise which resolves to a module with a default export containing a React component.
Do remember that the lazy component should be rendered inside a “Suspense component” because the suspense component will allow you to add fallback content as a loading state, while waiting for the lazy component to load.
Check out my best-selling Udemy course on ReactJS which has a huge collection of interview questions asked in real-world scenarios.
Founder and CEO of an IT company in India, I have more than 25 years experience of in dealing with people, processes, and codes. I started online training for my students when it was not in fashion and have trained more than 1000 students/working professionals personally which has helped them to secure awesome jobs or even start their own businesses.
I am also been an active corporate trainer for several years now and have been consulting with top Fortune 500/1000 companies to streamline their development projects efficiently. My goal is to share knowledge with a primary focus on advanced tools & techniques, projects, and standard programming practices to help my students understand the basics and fundamentals and make awesome technological implementations.