I understood how React components are loaded only when they are needed and display temporary content while those components are loading.
1.What is Lazy Loading?
It is used to load components only when they are required instead of loading all components at the beginning .
React provides lazy() function to implement lazy loading.
Example:
import {lazy} from 'react'; const Home = lazy(()=>import('./Home')) ; const Contact = lazy(()=>import('./Contact')); const About = lazy(()=>import('./About')); Here:
lazy() is used to load components dynamically.
import() loads the component when it is required.
Home,Contact,About can be loaded seperately.
This technique is called Code Splitting when it divides the application into smaller JavaScript chunks.
2.What is Suspense?
Suspense is a React component used to display fallback content while a lazy-loaded component is loading.
Example:
import {Suspense} from 'react'; <div> <Suspense fallback={<h1>{<h1>Component Loading...</h1>}</h1>}> </div> ** Here:**
Suspense handles the loading state.
Fallback displays temporary content.
Once the component loads ,React displays the actual component.
3.Lazy Loading with React Router:
we can use lazy loading with react router to load different pages
when users naviagte to them.
Example:
import { lazy, Suspense } from "react"; import { Routes, Route } from "react-router-dom"; const Home = lazy(() => import("./Home")); const Contact = lazy(() => import("./Contact")); const About = lazy(() => import("./About")); function App() { return ( <Suspense fallback={<h1>Component Loading...</h1>}> <Routes> <Route path="/" element={<Home />} /> <Route path="/contact" element={<Contact />} /> <Route path="/about" element={<About />} /> </Routes> </Suspense> ); } export default App; 4.Why do we use LazyLoading?
- It reduces the amount of Javascript loaded intitally.
- Components can be loaded when they are needed.
- It helps improve intial loading perfomance.
- It is useful for applications with multiple pages and components.