Introduction
As your React application grows, so does the size of your bundle, which can impact performance. Code splitting is a technique to split your code into smaller chunks that can be loaded on demand. This post will guide you through implementing code splitting in React using both JavaScript and TypeScript, with practical examples.
Understanding Code Splitting
Before diving into the implementation, let’s understand the impact of code splitting.
Before Code Splitting
Without code splitting, your entire application is bundled into a single file. This means that even if a user only visits one page or uses one component, they must download the entire application bundle. This can lead to:
- Longer Initial Load Time: Users have to wait longer for the initial load.
- Poor Performance on Slow Networks: Users with slower internet connections will experience significant delays.
- Unnecessary Data Transfer: Users download components and code they may never use.
After Code Splitting
With code splitting, your application is divided into smaller chunks that are loaded on demand. This results in:
- Faster Initial Load Time: Only the necessary chunks are loaded initially, speeding up the initial load.
- Improved Performance: Users experience faster load times and smoother interactions.
- Efficient Data Transfer: Only the required code is downloaded, reducing data usage.
JavaScript Implementation
Creating a Loadable Component
First, create a Loadable
component that will handle the loading state while your actual component is being loaded.
// src/components/Loadable.js
import { Suspense } from "react";
import Loader from "./Loader"; // Assume you have a Loader component const Loadable = (Component) => (props) => { return ( <Suspense fallback={<Loader />}> <Component {...props} />
</Suspense>
);
}; export default Loadable;
Example Usage with a Heavy Component
Let’s simulate a heavy component with some intensive computation to demonstrate the benefits of code splitting.
// src/components/HeavyComponent.js
import React, { useEffect, useState } from "react"; const HeavyComponent = () => { const [result, setResult] = useState(0); useEffect(() => { let sum = 0; for (let i = 0; i < 1e7; i++) { sum += i; } setResult(sum); }, []); return ( <div> <h1>Heavy Component</h1>
<p>Result of heavy computation: {result}</p>
</div>
);
}; export default HeavyComponent;
lets now import the heavy component into our main view
// src/App.js
import React from "react";
import Loadable from "./Loadable"; // use the Loadable component to asynchronously load the HeavyComponent const heavyLoadableComp = Loadable(React.lazy(() => import("./HeavyComponent"))); const App = () => { return ( <div> <h1>Welcome to My App</h1>
<LoadableHeavyComponent /> </div>
);
}; export default App;
TypeScript Implementation
Creating a Loadable Component in TypeScript
To ensure type safety and leverage TypeScript’s features, we can rewrite the Loadable component.
// src/components/Loadable.tsx
import React, { Suspense, ReactElement } from "react";
import Loader from "./Loader"; const Loadable = <P extends object>(Component: React.ComponentType<P>): React.FC<P> => (props: P): ReactElement => { return ( <Suspense fallback={<Loader />}> <Component {...props} />
</Suspense>
);
}; export default Loadable;
Example Usage with a Heavy Component in TypeScript
// src/App.tsx
import React from "react"; // use the Loadable component to asynchronously load the HeavyComponent const heavyLoadableComp = Loadable(React.lazy(() => import("./HeavyComponent"))); const App: React.FC = () => { return ( <div> <h1>Welcome to My App</h1>
<LoadableHeavyComponent /> </div>
);
}; export default App;
Code splitting is a powerful technique to optimize your React applications. By splitting your code into smaller chunks and loading them on demand, you can significantly improve the performance of your application, especially as it grows. Now go make a better react website!
if you like this simple guide, pls give some love ❤️ and even add to this guide