An open API service indexing awesome lists of open source software.

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

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
};
```