SnekNOTSnake
SnekNOTSnake

Reputation: 1407

React Code Splitting - Load other component after initial page

I just implemented Router-based code splitting (lazy load) in my app. AFAIK, when lazy load is implemented, a user visiting a page will only load a certain chunk of the whole bundle and nothing else.

So, is there a way where we can tell React to begin loading the other component after the initial page is loaded, so that the user don't have to wait when they jump to another page?

const App = React.lazy(() => import('./components/home/App'))
const Game = React.lazy(() => import('./components/game/Game'))
const Custom = React.lazy(() => import('./components/custom/Custom'))
const Credits = React.lazy(() => import('./components/credits/Credits'))
const Rules = React.lazy(() => import('./components/rules/Rules'))
const NotFound = React.lazy(() => import('./components/404/404'))

Upvotes: 1

Views: 1120

Answers (1)

SnekNOTSnake
SnekNOTSnake

Reputation: 1407

Thanks to Yash Joshi's enlightenment, I now realize what I'm trying to do is called "Preloading a component".

// component/home/App.js
// Preloading Game.js from App.js
const lazyWithPreload = (factory) => {
    const Component = React.lazy(factory)
    Component.preload = factory
    return Component
}
 
const Game = lazyWithPreload(() => import('../game/Game'))
 
const App = () => {
    React.useEffect(() => {
        Game.preload()
    }, [])
    return (<div>Something cool</div>)
}

lazyWithPreload preloads the component whenever and wherever I want, including when the initial page is loaded (which solves my problem).

Source: https://medium.com/hackernoon/lazy-loading-and-preloading-components-in-react-16-6-804de091c82d

Upvotes: 3

Related Questions