React.lazy() We can load a component dynamically with native React high order component and do not include it in a bundle. Import a component like const HeavyComponent = React.lazy(() => import("./HeavyComponent")) Integrate it into the code within <Suspense> </Suspense> component from React. Lazy component should be exported as default . Path of an imported lazy component can not be dynamic (bad news). On a button click a lazy component is loaded and additional chunk file is being downloaded, which is visible in the network tab of dev tools. Bring some synchronous code before a render with React.useLayoutEffect() hook, to imitate that file is big.
import { Suspense } from 'react';
import BasicComponent from '/components/helper_for_posts/BasicComponent';
function ComponentWithNativeLazyLoad() {
const [state, setState] = React.useState(false)
const HeavyComponent = React.lazy(() => import('/components/helper_for_posts/HeavyComponent.js'))
return (
<>
<button onClick={() => setState(!state)}>Toggle lazy components</button>
<BasicComponent />
{
state
? (
<Suspense fallback={<div style={{ color: 'red' }}>Loading...</div>}>
<HeavyComponent num='1' />
<HeavyComponent num='2' />
<HeavyComponent num='3' />
</Suspense>
)
: null
}
</>
)
}
// components/helper_for_posts/BasicComponent.js
import React from 'react'
import syncWait from '/functions/syncWait'
export default function BasicComponent() {
return (
<div>
Hello, I am not lazy.
</div>
)
}
// components/helper_for_posts/HeavyComponent.js
import React from 'react'
import syncWait from '/functions/syncWait'
export default function HeavyComponent(props) {
// do something for 1s before rendering
React.useLayoutEffect(syncWait, [])
return (
<div style={{ color: 'blue' }}>
Hello, I am lazy and heavy {props.num}.
</div>
)
}
// functions/syncWait.js
export default function syncWait(ms = 1000) {
const end = Date.now() + ms
while (Date.now() < end) continue
}