DeployU
Interviews / Frontend Engineering / This large component is slowing down initial load. Implement code splitting.

Questions

This large component is slowing down initial load. Implement code splitting.

practical Performance Interactive Quiz Code Examples

The Scenario

You’re working on a React application that includes a large AdminDashboard component. This dashboard is only accessible to users with administrator privileges.

Currently, the AdminDashboard component is directly imported and bundled with the main application code. This means that all users, including regular users who will never access the dashboard, download its code on initial page load. This is making the initial load time of the application unnecessarily slow.

The Challenge

Your task is to refactor the application to implement code splitting. Load the AdminDashboard component only when it’s actually needed (i.e., when the showAdmin flag is true).

Your Code
import React, { useState } from 'react';

// Simulate a large component that logs when it's loaded
function AdminDashboard() {
  console.log('AdminDashboard loaded!');
  return (
    <div style={{ border: '1px solid green', padding: '20px', margin: '10px' }}>
      <h2>Admin Dashboard</h2>
      <p>Welcome, Administrator!</p>
      <p>Here are your sensitive admin controls.</p>
    </div>
  );
}

export default function App() {
  const [showAdmin, setShowAdmin] = useState(false);

  return (
    <div style={{ padding: '20px' }}>
      <h1>Main Application</h1>
      <button onClick={() => setShowAdmin(!showAdmin)}>
        {showAdmin ? 'Hide Admin Dashboard' : 'Show Admin Dashboard'}
      </button>
      <hr />
      {/* THE BUG: AdminDashboard is statically imported and bundled,
          even if showAdmin is false. */}
      {showAdmin && <AdminDashboard />}
      {!showAdmin && <p>Admin Dashboard is currently hidden.</p>}
    </div>
  );
}
Click "Run Code" to see output...
Click "Run Code" to see test results...

The Explanation: Improving Performance with Code Splitting

How Different Experience Levels Approach This
Junior Engineer
Surface Level

[object Object]

Senior Engineer
Production Ready

[object Object]

What Makes the Difference?
  • Context over facts: Explains when and why, not just what
  • Real examples: Provides specific use cases from production experience
  • Trade-offs: Acknowledges pros, cons, and decision factors

The Problem with Static Imports

The AdminDashboard component is being statically imported. This means that even if showAdmin is false and the component is not rendered, its JavaScript code is still included in the main application bundle and downloaded by the browser on initial load. For large components, this significantly increases the initial bundle size and slows down the application’s startup time.

The Fix: Dynamic Imports with React.lazy and React.Suspense

Code splitting is a technique that allows you to split your code into smaller chunks, which can then be loaded on demand. React provides built-in support for code splitting using React.lazy and React.Suspense.

  • React.lazy(): This function lets you render a dynamic import as a regular component. It takes a function that returns a Promise, which resolves to a module with a default export (your component).
  • React.Suspense: This component lets you display a fallback UI (like a loading spinner) while the lazy-loaded component is being downloaded.

Here is the corrected implementation:

import React, { useState, Suspense } from 'react';

// FIX: Use React.lazy to dynamically import the AdminDashboard component.
// This tells Webpack (or your bundler) to create a separate chunk for it.
const AdminDashboard = React.lazy(() => {
  console.log('AdminDashboard module is being downloaded...');
  return new Promise(resolve => setTimeout(() => {
    // Simulate network delay for loading the chunk
    resolve(import('./AdminDashboard'));
  }, 1000));
});

// In a real project, AdminDashboard would be in its own file:
// AdminDashboard.jsx
// function AdminDashboard() {
//   console.log('AdminDashboard loaded!');
//   return (
//     <div style={{ border: '1px solid green', padding: '20px', margin: '10px' }}>
//       <h2>Admin Dashboard</h2>
//       <p>Welcome, Administrator!</p>
//       <p>Here are your sensitive admin controls.</p>
//     </div>
//   );
// }
// export default AdminDashboard;


export default function App() {
  const [showAdmin, setShowAdmin] = useState(false);

  return (
    <div style={{ padding: '20px' }}>
      <h1>Main Application</h1>
      <button onClick={() => setShowAdmin(!showAdmin)}>
        {showAdmin ? 'Hide Admin Dashboard' : 'Show Admin Dashboard'}
      </button>
      <hr />
      {/* FIX: Wrap the lazy-loaded component with Suspense */}
      <Suspense fallback={<div>Loading Admin Dashboard...</div>}>
        {showAdmin && <AdminDashboard />}
        {!showAdmin && <p>Admin Dashboard is currently hidden.</p>}
      </Suspense>
    </div>
  );
}

With this change, the code for AdminDashboard will only be downloaded by the browser when showAdmin becomes true and the component is actually rendered. This significantly improves the initial load time for users who don’t need the dashboard.

Practice Question

What is the primary benefit of implementing code splitting in a React application?