Skip to content

Commit

Permalink
[FEATURE] - preload components on intial load to prevent rerendering …
Browse files Browse the repository at this point in the history
…after hydrate
  • Loading branch information
michaelBenin committed Dec 20, 2017
1 parent b3dbe73 commit 4d62b2d
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 10 deletions.
38 changes: 29 additions & 9 deletions src/client/index.js
@@ -1,5 +1,8 @@
import P from 'bluebird';
import React from 'react';
import { hydrate, render } from 'react-dom';
import matchRoutes from 'react-router-config/matchRoutes';
import routes from '../react_router/react_router';
import createHistory from 'history/createBrowserHistory';
import scriptJS from 'scriptjs';
import get from 'lodash/get';
Expand Down Expand Up @@ -42,15 +45,32 @@ function bootReact() {
document.documentElement.className === '' ? 'hydrated' : ' hydrated';
}

try {
hydrate(
<Root store={store} history={browserHistory} />,
window.document,
renderedApp
);
} catch (err) {
// fire ad code here to still show ads
log.fatal(`Unable to render app: ${err.message}`, err.stack);
// eslint-disable-next-line no-restricted-globals
const branch = matchRoutes(routes, location.pathname);
const preloadChunks = branch.reduce(function matchMap(list, { route }) {
if (route.preloadChunk) {
list.push(route.preloadChunk);
}
return list;
}, []);

function hydrateApp() {
try {
hydrate(
<Root store={store} history={browserHistory} />,
window.document,
renderedApp
);
} catch (err) {
// fire ad code here to still show ads
log.fatal(`Unable to render app: ${err.message}`, err.stack);
}
}

if (preloadChunks.length) {
P.all(preloadChunks.map(chunk => chunk())).then(hydrateApp);
} else {
hydrateApp();
}

if (module.hot) {
Expand Down
Expand Up @@ -2,10 +2,15 @@ import React from 'react';
import Loadable from 'react-loadable';
import searchResultsStateManager from './search_results_data_fetch';

let CachedComponent = false;

const LazySearchResultsPage = Loadable({
loader: () =>
import(/* webpackChunkName: "search" */ './search_results_page').then(
resp => resp.default
resp => {
CachedComponent = resp.default;
return CachedComponent;
}
),
loading() {
return (
Expand All @@ -24,8 +29,19 @@ export default {
const SearchResultsPage = require('./search_results_page').default;
return <SearchResultsPage />;
}
if (CachedComponent) {
return <CachedComponent />;
}
return <LazySearchResultsPage />;
},
loadData: searchResultsStateManager,
preloadChunk() {
return import(/* webpackChunkName: "search" */ './search_results_page').then(
resp => {
CachedComponent = resp.default;
return CachedComponent;
}
);
},
chunk: 'search'
};

0 comments on commit 4d62b2d

Please sign in to comment.