How to dynamically load module in React.js ? – GeeksforGeeks

Improve Article

Save Article

Like Article

Improve Article

Save Article

In this article, you will understand to import and load the modules or components dynamically in ReactJS. In ReactJS loading of modules statically is cumbersome as it loads the modules beforehand even if it 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. 

Let’s understand using step-by-step implementation. 

Steps to create react application:

Step 1: Use create-react-app to build react

npm create-react-app <project_name>

Step 2: Go to <project_name>

cd <project_name>

Project Structure: The project looks something like this.

 

Example 1: In this example, we will recognize the static load of resources in ReactJS. Let’s suppose we have a component that displays text and that is imported statically from another file into the main file. It gets loaded beforehand. We have two files index.js and app.js.

File: index.js

Javascript

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'));

File: app.js

Javascript

import React from 'react';

import ReactDom from 'react-dom'

  

class Text extends React.Component {

  

    constructor(props) {

        super(props);

    }

  

    render() {

        return (

            <p>The Content is loaded on GeeksforGeeks....</p>

        )

    }

}

  

export default Text;

Output:

 

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.

Approach: 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. We again have two files  index.js and app.js where the app.js is loaded dynamically using <Suspense> and React.lazy( )

File: index.js

Javascript

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'));

File: app.js

Javascript

import React from 'react';

import ReactDom from 'react-dom'

  

class Text extends React.Component {

  

    constructor(props) {

        super(props);

    }

  

    render() {

        return (

            <p>The Content is loaded on GeeksforGeeks....</p>

        )

    }

}

  

export default Text;

Output:

 

 

Stay connected with us on social media platform for instant update click here to join our  Twitter, & Facebook We are now on Telegram. Click here to join our channel (@TechiUpdate) and stay updated with the latest Technology headlines. For all the latest Technology News Click Here 

Read original article here

Denial of responsibility! FineRadar is an automatic aggregator around the global media. All the content are available free on Internet. We have just arranged it in one platform for educational purpose only. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials on our website, please contact us by email – abuse@fineradar.com. The content will be deleted within 24 hours.
dynamicallyfineradar updateFree Fire Redeem Codesgadget updateGeeksforGeeksLatest tech newsloadmoduleReact.jsTech Headlinestech newsTech News UpdatesTechnologyTechnology News
Comments (0)
Add Comment