Last active
February 13, 2019 03:24
-
-
Save heldr/d01f76389799b257ce061ac78c05666d to your computer and use it in GitHub Desktop.
React hooks load page chunk (code splitting)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { Router } from "@reach/router"; | |
import LoadComponent from './LoadComponent'; | |
const FoobarLoader = () => import('./pages/Foobar'); | |
const App: React.StatelessComponent<{}> = () => ( | |
<div> | |
<Router> | |
<LoadComponent componentAsPromised={FoobarLoader} path="foobar" /> | |
</Router> | |
</div> | |
); | |
export default App; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect, createElement, FunctionComponent } from 'react'; | |
import { RouteComponentProps } from '@reach/router'; | |
interface Chunk { | |
default: FunctionComponent<RouteComponentProps> | |
} | |
interface Props extends RouteComponentProps { | |
componentAsPromised: () => Promise<Chunk> | |
} | |
const BeforeLoad = <React.Fragment />; // or Loading Message | |
const LoadComponent: FunctionComponent<Props> = ({ componentAsPromised, ...props }) => { | |
const [renderer, render] = useState(BeforeLoad); | |
const onLoadComponent = ({ default: LoadedComponent }: Chunk) => render(createElement(LoadedComponent, props)); | |
useEffect(() => { | |
componentAsPromised().then(onLoadComponent); | |
}); | |
return renderer; | |
} | |
export default LoadComponent; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment