How to use static loading Component In ReactJS

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 w3wiki....
            </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.

How to dynamically load module in React.js ?

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. 

Similar Reads

Prerequisite

React JS React JS Class Component React JS lazy loading...

Steps to Create the React application

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

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....

Dynamically loading module using React.lazy()

...