Code splitting and Activity

Topic 4 of 4 in Performance7 min readIntermediateFree course

Overview

Two performance problems show up as apps grow:

  1. The JavaScript bundle gets big. Every page, editor, chart library and admin screen is downloaded before the first screen appears — even if most users never open them.
  2. Switching views throws away work. Conditionally rendering tabs unmounts them, losing scroll positions, drafts and loaded data, and re-creating them when users return.

Code splitting fixes the first; React’s <Activity> fixes the second.

Code splitting with lazy

One big bundle: app.js is 900 KB containing home, courses, editor, admin and charts, and everything downloads before the first screen appears. Split by route: app.js is 180 KB and loads first; editor.js, 420 KB, loads when /editor opens; admin.js, 300 KB, loads for admins only. Code: const Editor = lazy(() => import(‘./Editor.jsx’)) rendered inside a Suspense boundary with a Spinner fallback.

A dynamic import() tells Vite to put a module in its own chunk, downloaded only when the import runs. React’s lazy turns that into a component:

JSX
import { lazy, Suspense, useState } from 'react';

const CourseEditor = lazy(() => import('./CourseEditor.jsx'));

function CoursePage({ course }) {
  const [isEditing, setIsEditing] = useState(false);

  return (
    <>
      <h1>{course.title}</h1>
      <button onClick={() => setIsEditing(true)}>Edit</button>
      {isEditing && (
        <Suspense fallback={<p>Loading editor…</p>}>
          <CourseEditor course={course} />
        </Suspense>
      )}
    </>
  );
}
  • lazy takes a function returning a promise for a module with a default export.
  • The first time <CourseEditor> renders, React starts the download and suspends; the nearest <Suspense> shows its fallback.
  • Once loaded, the module is cached — later renders are instant.

Declare lazy components at the top level of a module, never inside another component (that would create a new lazy component each render and reset its state).

For a named export: lazy(() => import('./charts.jsx').then((m) => ({ default: m.SalesChart }))).

What to split

  1. Routes — the biggest win. Most users visit a few pages per session. With React Router data mode, use the route’s lazy property (see Nested routes and layouts), which loads code in parallel with the route’s data.
  2. Heavy, occasional features — rich-text editors, charts, maps, PDF viewers, admin panels.
  3. Below-the-fold or interaction-triggered UI — modals, settings panels.

Don’t split tiny components: every chunk is a separate request, and a waterfall of small requests can be slower than one medium file.

Preloading

Start a download before the user needs it — for example, when they hover the “Edit” button:

JSX
const loadEditor = () => import('./CourseEditor.jsx');
const CourseEditor = lazy(loadEditor);

<button onMouseEnter={loadEditor} onFocus={loadEditor} onClick={() => setIsEditing(true)}>
  Edit
</button>

The import is cached, so when lazy calls it later, the code is already there (or on its way).

Checking your bundle

npm run build prints every chunk and its size. For a visual breakdown, add a bundle visualiser plugin (such as rollup-plugin-visualizer) and look for large dependencies that only a few pages use.

Activity: hide without losing state

Conditional rendering destroys state:

JSX
{tab === 'notes' && <Notes />}   // switching away unmounts Notes: the typed draft is gone

<Activity> keeps the subtree mounted but hidden:

JSX
import { Activity } from 'react';

<Activity mode={tab === 'notes' ? 'visible' : 'hidden'}>
  <Notes />
</Activity>

Conditional rendering: switching away unmounts Notes, and its typed draft and scroll position are lost. Activity with mode visible or hidden: when hidden, Notes is kept in memory and its effects are paused; when visible again, the draft is still there. Hidden content renders at low priority, so Activity can also pre-render a screen the user will visit next.

In hidden mode, React:

  • hides the children visually (with display: none),
  • keeps their state and DOM, so drafts, scroll positions and form values survive,
  • cleans up their effects (subscriptions, timers stop) and re-runs them when visible again,
  • still applies updates to the hidden subtree, at low priority, so it’s ready when shown.

It’s like CSS hiding, but with effects properly paused and without the hidden UI competing with visible UI for rendering time.

Pre-rendering likely next screens

Because hidden content renders in the background at low priority, you can prepare a screen before the user opens it:

JSX
<Activity mode="hidden">
  <CheckoutPage />   {/* renders, loads its data and code in the background */}
</Activity>

When the user clicks “Checkout”, switching to visible is instant. Combined with Suspense data fetching, data requests start early too.

Activity and memory

Hidden trees stay in memory. That’s fine for a few tabs or recently visited screens, but don’t keep hundreds of hidden pages around. A common pattern is to keep the last few screens in Activity and unmount older ones.

Activity and effects

Because effects are cleaned up when hidden, components inside Activity must handle setup → cleanup → setup correctly — exactly what StrictMode already tests. Media is a special case: a <video> keeps playing when hidden with display: none, so pause it in an effect’s cleanup:

JSX
useLayoutEffect(() => {
  const video = videoRef.current;
  return () => video.pause();
}, []);

Putting it together

Lazy loading and Activity combine naturally: tabs whose code is downloaded on first visit and whose state survives switching — the exercise for this lesson.

Measure the effect: use the Network tab to confirm chunks load on demand, and Lighthouse or your hosting analytics to track how quickly the first screen appears for real users.

Exercise

Lazy tabs that keep their state

Build CourseWorkspace with three tabs: “Lessons”, “Notes” and “Quiz”. Notes and Quiz are loaded with lazy() from separate files, inside a Suspense boundary with a “Loading tab…” fallback. Use <Activity> so each tab that has been opened keeps its state (for example, text typed in Notes) when you switch away and back. Only render a tab’s Activity once it has been visited, so Quiz’s code isn’t downloaded until someone opens it.

JavaScript
import { Activity, lazy, Suspense, useState } from 'react';

const Notes = lazy(() => import('./Notes.jsx'));
const Quiz = lazy(() => import('./Quiz.jsx'));

function Lessons() {
  return <p>Lesson list…</p>;
}

export function CourseWorkspace() {
  // your code here
}

Summary

  • Code splitting breaks your bundle into chunks that load on demand, so the first screen loads faster.
  • lazy(() => import('./X.jsx')) loads a component’s code the first time it renders; wrap it in <Suspense>.
  • Split by route first, then by heavy, rarely used features (editors, charts, admin screens).
  • <Activity mode="hidden"> hides UI while keeping its state and DOM, and pauses its effects.
  • Hidden Activity content renders at low priority, so it can also pre-render screens users are likely to open next.