React Code-Splitting

Speed up your React app with dynamic imports

[React TypeScript] Code Spliting

React.lazy & Suspense SplitMe.tsx

import React from 'react';

const SplitMe: React.FC = () => {
    return <div>SplitMe</div>;
};

export default SplitMe;

App.tsx

import React, { useState, Suspense } from 'react';
	
const SplitMe = React.lazy(() => import('./SplitMe'));

const App: React.FC = () => {
    const [visible, setVisible] = useState(false);

    const onClick = () => {
        setVisible(true);
    };
	    
    return (
        <>
            <div onClick={onClick}>Hello React</div>
            <Suspense fallback={<div>loading...</div>}>
                {visible && <SplitMe />}
            </Suspense>
        </>
    );
};
	
export default App;

Loadable Components

install

$ yarn add @loadable-component  
$ yarn add --dev @types/loadable__component

App.tsx

import React, { useState } from 'react';
import loadable from '@loadable/component';

const SplitMe = loadable(() => import('./SplitMe'), {
    fallback: <div>loading...</div>,
});

const App: React.FC = () => {
    const [visible, setVisible] = useState(false);

    const onClick = () => {
        setVisible(true);
    };
    return (
        <>
            <div onClick={onClick}>Hello React</div>
            {visible && <SplitMe />}
        </>
    );
};

export default App;