Full dynamic import

Webpack accepts full dynamic imports, you can use them to create a reusable Loadable Component.

import loadable from '@loadable/component'
const AsyncPage = loadable(props => import(`./${props.page}`))
function MyComponent() {
return (
<div>
<AsyncPage page="Home" />
<AsyncPage page="Contact" />
</div>
)
}

Use a dynamic property

If you use Babel plugin, dynamic properties are supported out of the box. Else you have to add cacheKey function: it takes props and returns a cache key.

import loadable from '@loadable/component'
const AsyncPage = loadable(props => import(`./${props.page}`), {
cacheKey: props => props.page,
})
function MyComponent() {
const [page, setPage] = useState('Home')
return (
<div>
<button onClick={() => setPage('Home')}>Go to home</button>
<button onClick={() => setPage('Contact')}>Go to contact</button>
{page && <AsyncPage page={page} />}
</div>
)
}