Skip to content

Instantly share code, notes, and snippets.

@charisTheo
Created August 21, 2021 19:16
Show Gist options
  • Save charisTheo/d5e8dddd89430611ea708fb6c95e0a18 to your computer and use it in GitHub Desktop.
Save charisTheo/d5e8dddd89430611ea708fb6c95e0a18 to your computer and use it in GitHub Desktop.
import React, { useState } from 'react'
const Button = () => {
const [ LazyComponent, setLazyComponent ] = useState(null)
const loadLazyComponent = async () => {
if (LazyComponent !== null) {
return
}
// import default export of `lazy.js` module
const { default: lazyModule} = await import('./lazy')
// create React component so it can be rendered
const LazyElement = React.createElement(lazyModule, {
// pass props to component here
whatAmI: "lazy! 🤤"
})
setLazyComponent(LazyElement)
}
return (
<>
<button onClick={loadLazyComponent}>Lazy load component</button>
{LazyComponent}
</>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment