React JS: How to load only page related js, css and html on production mode?

Viewed 517

When we build the react project on production mode. It creates only one index.html, CSS and JS file. so while accessing the project on browser it takes lots of time to load because of the big size of JS and CSS files.

So is there any way to load only the page related JS, CSS and HTML. Or can we create page wise files while creating the production build?

2 Answers

You might want to consider using React.lazy. Which will load your component file only when your component is trying to load and render for the first time.

This will automatically load the bundle containing the OtherComponent when this component is first rendered.

For example I'm using this for my routes like below :

[
        {
            path: '/apps/role/roles/:roleId',
            component: React.lazy(() => import('./role/Role')),
        }
]

You will notice separate bundle file is generated and also when you load Role it will load respective bundle file.

Related