Skip to content

Instantly share code, notes, and snippets.

@nekitk
Last active January 18, 2022 18:51
Show Gist options
  • Save nekitk/1241942f23824b031b5d26190bd50359 to your computer and use it in GitHub Desktop.
Save nekitk/1241942f23824b031b5d26190bd50359 to your computer and use it in GitHub Desktop.
import React from 'react'
export const getLazyComponent = (componentImport) => {
const LazyComponent = React.lazy(componentImport)
return () => (
<LazyComponentErrorBoundary>
<React.Suspense fallback={'Loading...'}>
<LazyComponent />
</React.Suspense>
</LazyComponentErrorBoundary>
)
}
class LazyComponentErrorBoundary extends React.Component {
state = {
error: false,
}
static getDerivedStateFromError() {
return { error: true }
}
render() {
return this.state.error
? 'Failed to load component, please refresh the page to try again'
: this.props.children
}
}
// Usage with default export
const LazyDefaultComponent = getLazyComponent(() => import('./MyComponent'))
// Usage with named export
// See https://github.com/reactjs/rfcs/blob/gaearon-patch-2/text/0000-lazy.md#why-the-default-field
const LazyNamedComponent = getLazyComponent(() =>
import('./MyComponent').then((res) => ({ default: res.MyComponent }))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment