Skip to content

Instantly share code, notes, and snippets.

@heldr
Last active February 13, 2019 03:24
Show Gist options
  • Save heldr/d01f76389799b257ce061ac78c05666d to your computer and use it in GitHub Desktop.
Save heldr/d01f76389799b257ce061ac78c05666d to your computer and use it in GitHub Desktop.
React hooks load page chunk (code splitting)
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;
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