How to dynamically load module in React.js ?
Last Updated :
25 Jul, 2024
In React JS loading of modules statically is cumbersome as it loads the modules beforehand even if it is not rendered. Some components render only when the user interacts, so in such cases, it can lead to more resource consumption. When you statically import modules, you are loading larger data than you may actually need, which could lead to a slower initial page load. To solve this problem we import the modules dynamically. Further, will understand how this can be done.
Prerequisite
Let's understand using step-by-step implementation.
Steps to Create the React application
Step 1: Use create-react-app to build a react
npm create-react-app <project_name>
Step 2: Move to the project directory
cd <project_name>
Project Structure:
Using static loading Component
Example: This example recognize the static load of resources in ReactJS. The component displays text and that is imported statically from another file into the main file. It gets loaded beforehand.
JavaScript
// Filename - index.js
import React from 'react';
import * as ReactDom from 'react-dom';
import App from './app'
const Btn = () => {
const [disp, setDisp] = React.useState(true);
return (disp) ? (<button onClick={() =>
setDisp(false)}>Click Me</button>) : <App />
}
ReactDom.render(<Btn />, document.getElementById('root'));
JavaScript
// Filename - App.js
import React from "react";
import ReactDom from "react-dom";
class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<p>
The Content is loaded on GeeksforGeeks....
</p>
);
}
}
export default App;
Steps to Run the Application: Use this command in the terminal in the project directory.
npm start
Output: This output will be visible on http://localhost:3000/ in the browser
Explanation: In the above example, the 0.chunk.js is loaded beforehand immediately when the app loads. Here the modules are imported at the compile time.
Dynamically loading module using React.lazy()
To import the modules dynamically ReactJS supports React.lazy( ) method. This method accepts a function as an argument and renders the component as a regular component and the function must call the import( ) that returns a promise. This is used along with <Suspense> because it allows us to display the fallback content while we are waiting for the module to load.
Example: This example lazy load the app component when the button is clicked to imnplement dynamic loading.
JavaScript
// Filename - App.js
import React from 'react';
import * as ReactDom from 'react-dom';
const Component = React.lazy(() => import('./app'))
const Btn = () => {
const [disp, setDisp] = React.useState(true);
return (disp) ? (<button onClick={() =>
setDisp(false)}>Click Me</button>) :
(<React.Suspense fallback={<div>Loading...</div>}>
<Component />
</React.Suspense>)
}
ReactDom.render(<Btn />, document.getElementById('root'));
JavaScript
import React from "react";
class Text extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<p>
The Content is loaded on GeeksforGeeks....
</p>
);
}
}
export default Text;
Steps to Run the Application: Use this command in the terminal in the project directory.
npm start
Output: This output will be visible on http://localhost:3000/ in the browser.
Similar Reads
How to Dynamically Load JS inside JS? In JavaScript, dynamically loading scripts allows the inclusion of external JavaScript files only when needed, improving performance and efficiency. Instead of using static imports, scripts can be loaded conditionally at runtime. ApproachES6 provides us with a construct import(), which provides the
2 min read
How to modularize code in ReactJS ? Modularize code in React JS refers to dividing it into segments or modules, where each file is responsible for a feature or specific functionality. React code can easily be modularized by using the component structure. The approach is to define each component into different files. With each componen
3 min read
How to add Chatbot in React JS Project ? In today's digital world, chatbots have become an integral part of many websites and applications. They provide a convenient and efficient way to interact with users, answer their queries, and improve overall user experience. If you're working on a React JS project and want to incorporate a chatbot,
3 min read
How to have path alias in Node.js ? Node.js has tons of modules that can be very hard to deal with. Thus, it's a good practice to have a neat and well-defined directory structure. In this article, we are going to deal with a problem that involves the Node.js modules. Â Let's first understand what is the need to have path alias. There a
3 min read
How to Access Props Inside Quotes in React JSX? Props are used to pass data from parent to child components in react. We can access the props inside quotes in JSX like HTML attribute with the help of ES6 Template Literals and javascript expressions with curly bracesApproachTo access Props inside quotes in React JS we will use the curly braces {}
2 min read