https://github.com/devjubayr/react_lazy_load
Implementing react lazy load, utilizing component to render if the UI need this. With suspense
https://github.com/devjubayr/react_lazy_load
Last synced: 6 days ago
JSON representation
Implementing react lazy load, utilizing component to render if the UI need this. With suspense
- Host: GitHub
- URL: https://github.com/devjubayr/react_lazy_load
- Owner: devjubayr
- Created: 2025-10-06T12:20:53.000Z (10 months ago)
- Default Branch: main
- Last Pushed: 2025-10-06T13:30:51.000Z (10 months ago)
- Last Synced: 2026-07-16T02:34:27.801Z (6 days ago)
- Language: JavaScript
- Size: 30.3 KB
- Stars: 2
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# 💤 React Lazy Load (Main Component Explanation)
In this example, **lazy loading** is implemented in the main `App.jsx` file using `React.lazy()` and `Suspense`.
### 📘 `App.jsx` Explanation
```jsx
import { Suspense, useState } from "react";
import { importFile } from "./utils/importFile";
const components = [
{ path: "todos", btnLabel: "Todos" },
{ path: "posts", btnLabel: "Posts" },
];
function App() {
const [component, setComponent] = useState(null);
const selectComp = async (path) => {
const Comp = await importFile(path); // dynamically imports the component
setComponent(); // sets the component to render
};
return (
{components.map((comp) => (
selectComp(comp.path)}
className="bg-gray-600 p-2 rounded-sm"
>
{comp.btnLabel}
))}
{/* Suspense shows fallback while component is being loaded */}
Loading...}>{component}
);
}
export default App;
```
```jsx
import React from "react";
export const importFile = (file) => {
return React.lazy(() => import(`../components/${file}`)); // returns a promise
};
```