JavaScript and React course ยท Module 8: Advanced React Patterns

Concurrent Mode and Suspense

5 min read ยท
In this lesson9

Imagine a mission control center on a space station where hundreds of signals from different sensors are processed simultaneously. Some data is urgent (alarms), others less so (weather statistics from distant planets). React Concurrent Mode works on a similar principle - it allows you to prioritize interface updates so that the application remains responsive even during heavy operations.

What is Concurrent Mode?

Concurrent Mode is a set of mechanisms in React that allow interrupting and resuming rendering. Traditionally, React rendered synchronously - when it started an update, it had to finish it before it could react to anything else. In concurrent mode, React can:

  • Start rendering an update
  • Interrupt it when a more urgent update appears
  • Return to the interrupted work later

It is like a space controller who can set aside analyzing data from a distant probe when a sudden alert about an approaching asteroid appears.

startTransition - prioritizing updates

startTransition is an API that tells React: "this update is not urgent, you can interrupt it." It is ideal for operations that can wait a moment, like filtering a large list or navigating between tabs.

import { useState, startTransition } from 'react';

function GalaxySearch() {
  const [searchInput, setSearchInput] = useState('');
  const [searchResults, setSearchResults] = useState([]);

  const handleSearch = (value) => {
    // Updating the input is URGENT - the user must see what they type
    setSearchInput(value);

    // Filtering results is LESS URGENT
    startTransition(() => {
      const filtered = galaxyDatabase.filter(
        galaxy => galaxy.name.toLowerCase().includes(value.toLowerCase())
      );
      setSearchResults(filtered);
    });
  };

  return (
    <div>
      <input
        value={searchInput}
        onChange={(e) => handleSearch(e.target.value)}
        placeholder="Search galaxies..."
      />
      <GalaxyList results={searchResults} />
    </div>
  );
}

Thanks to startTransition, the input responds immediately to typing, even if filtering thousands of galaxies takes a moment.

useTransition - tracking transition state

useTransition is a hook that, in addition to startTransition, gives us an isPending flag indicating whether a transition is in progress:

import { useState, useTransition } from 'react';

function MissionDashboard() {
  const [activeTab, setActiveTab] = useState('overview');
  const [isPending, startTransition] = useTransition();

  const switchTab = (tab) => {
    startTransition(() => {
      setActiveTab(tab);
    });
  };

  return (
    <div>
      <nav>
        {['overview', 'crew', 'systems', 'navigation'].map(tab => (
          <button
            key={tab}
            onClick={() => switchTab(tab)}
            style={{
              opacity: isPending && activeTab !== tab ? 0.7 : 1,
              fontWeight: activeTab === tab ? 'bold' : 'normal',
            }}
          >
            {tab.toUpperCase()}
          </button>
        ))}
      </nav>

      {isPending && <div className="loading-bar">Loading panel...</div>}

      <TabContent tab={activeTab} />
    </div>
  );
}

Suspense - declarative waiting for data

Suspense is a component that allows you to "suspend" rendering until data is ready. Instead of manually managing loading states, you declare what to show while waiting:

import { Suspense } from 'react';

function SpaceStation() {
  return (
    <div>
      <h1>Space Station Alpha</h1>

      <Suspense fallback={<LoadingSpinner message="Loading crew data..." />}>
        <CrewList />
      </Suspense>

      <Suspense fallback={<LoadingSpinner message="Checking systems..." />}>
        <SystemsStatus />
      </Suspense>
    </div>
  );
}

Each section loads independently - the user sees the crew data as soon as it is ready, without waiting for the systems status.

Suspense with lazy loading

The most common use of Suspense is loading components dynamically using React.lazy:

import { lazy, Suspense } from 'react';

// Dynamically loaded components
const StarMap = lazy(() => import('./StarMap'));
const MissionLog = lazy(() => import('./MissionLog'));
const CrewManagement = lazy(() => import('./CrewManagement'));

function CommandCenter() {
  const [view, setView] = useState('map');

  return (
    <div>
      <nav>
        <button onClick={() => setView('map')}>Star Map</button>
        <button onClick={() => setView('log')}>Mission Log</button>
        <button onClick={() => setView('crew')}>Crew</button>
      </nav>

      <Suspense fallback={<div>Loading module...</div>}>
        {view === 'map' && <StarMap />}
        {view === 'log' && <MissionLog />}
        {view === 'crew' && <CrewManagement />}
      </Suspense>
    </div>
  );
}

Nested Suspense

We can nest Suspense components, creating a loading hierarchy. The outer Suspense catches everything, while inner ones allow for more granular control:

function MissionControl() {
  return (
    <Suspense fallback={<FullPageLoader />}>
      <header>
        <MissionTitle />
      </header>

      <main>
        <Suspense fallback={<SectionLoader text="Map..." />}>
          <InteractiveStarMap />
        </Suspense>

        <aside>
          <Suspense fallback={<SectionLoader text="Statistics..." />}>
            <MissionStats />
          </Suspense>

          <Suspense fallback={<SectionLoader text="Messages..." />}>
            <CommunicationLog />
          </Suspense>
        </aside>
      </main>
    </Suspense>
  );
}

useDeferredValue - deferred values

useDeferredValue is a hook that allows you to defer the update of a value. React first renders with the previous value (urgent update), then with the new one (less urgent):

import { useState, useDeferredValue, useMemo } from 'react';

function PlanetExplorer() {
  const [filter, setFilter] = useState('');
  const deferredFilter = useDeferredValue(filter);

  // The list renders with the deferred filter value
  const filteredPlanets = useMemo(() => {
    return allPlanets.filter(p =>
      p.name.toLowerCase().includes(deferredFilter.toLowerCase())
    );
  }, [deferredFilter]);

  const isStale = filter !== deferredFilter;

  return (
    <div>
      <input
        value={filter}
        onChange={(e) => setFilter(e.target.value)}
        placeholder="Filter planets..."
      />
      <div style={{ opacity: isStale ? 0.6 : 1 }}>
        {filteredPlanets.map(planet => (
          <PlanetCard key={planet.id} planet={planet} />
        ))}
      </div>
    </div>
  );
}

When to use each API?

APIUse caseExample
startTransitionUpdates that can waitChanging filters, navigating between tabs
useTransitionSame as above + loading indicatorSwitching views with loading state
SuspenseWaiting for data or codeLazy loading, data fetching
useDeferredValueDeferring value renderingFiltering large lists, search

Summary

Concurrent Mode and Suspense are like an advanced priority management system on a space station. Instead of processing all signals sequentially (blocking important alerts while analyzing less important data), React can intelligently prioritize updates:

  • startTransition allows marking less urgent updates
  • useTransition additionally reports the transition state
  • Suspense declaratively manages waiting for data
  • useDeferredValue defers expensive renders

These mechanisms work together, creating responsive interfaces even in complex applications with large amounts of data and heavy operations.

Code for this lesson: App.jsx
import React, { useState, useTransition, useDeferredValue, Suspense, lazy, useMemo } from 'react';

// ============================================
// DEMO: Concurrent Mode i Suspense
// ============================================

// Simulating a slow API
function fetchGalaxies(filter) {
  return new Promise(resolve => {
    setTimeout(() => {
      const allGalaxies = [
        'Milky Way', 'Andromeda', 'Triangulum', 'Sombrero',
        'Whirlpool', 'Black Eye', 'Centaurus A', 'Cygnus A',
        'Large Magellanic Cloud', 'Small Magellanic Cloud',
        'NGC 1300', 'NGC 4414', 'Messier 87', 'Pinwheel',
        'Cartwheel', 'Hoag', 'Sunflower', 'Tadpole',
      ];
      const filtered = allGalaxies.filter(g =>
        g.toLowerCase().includes(filter.toLowerCase())
      );
      resolve(filtered);
    }, 800);
  });
}

// --- SECTION 1: startTransition and useTransition ---
function GalaxySearch() {
  const [searchInput, setSearchInput] = useState('');
  const [searchResults, setSearchResults] = useState([]);
  const [isPending, startTransition] = useTransition();

  const handleSearch = async (value) => {
    setSearchInput(value);

    startTransition(async () => {
      const results = await fetchGalaxies(value);
      setSearchResults(results);
    });
  };

  return (
    <section style={sectionStyle}>
      <h2 style={headingStyle}>useTransition - Galaxy search</h2>
      <p style={{ fontSize: '13px', opacity: 0.7, marginBottom: '12px' }}>
        Type a galaxy name. Input responds immediately, the list updates with a delay.
      </p>
      <input
        value={searchInput}
        onChange={(e) => handleSearch(e.target.value)}
        placeholder="Search galaxies..."
        style={inputStyle}
      />
      <div style={{ opacity: isPending ? 0.5 : 1, transition: 'opacity 0.3s' }}>
        {isPending && <p style={{ color: '#ffd700' }}>Searching the cosmos...</p>}
        {searchResults.length > 0 ? (
          <ul style={{ listStyle: 'none', padding: 0 }}>
            {searchResults.map((galaxy, i) => (
              <li key={i} style={listItemStyle}>{galaxy}</li>
            ))}
          </ul>
        ) : (
          !isPending && searchInput && <p style={{ opacity: 0.5 }}>No results</p>
        )}
      </div>
    </section>
  );
}

// --- SECTION 2: useDeferredValue ---
function HeavyPlanetList({ filter }) {
  const planets = useMemo(() => {
    const allPlanets = [];
    for (let i = 1; i <= 200; i++) {
      allPlanets.push(`Planet-${String(i).padStart(3, '0')}`);
    }
    return allPlanets.filter(p =>
      p.toLowerCase().includes(filter.toLowerCase())
    );
  }, [filter]);

  return (
    <ul style={{ listStyle: 'none', padding: 0, maxHeight: '200px', overflowY: 'auto' }}>
      {planets.map((planet, i) => (
        <li key={i} style={listItemStyle}>{planet}</li>
      ))}
    </ul>
  );
}

function DeferredValueDemo() {
  const [filter, setFilter] = useState('');
  const deferredFilter = useDeferredValue(filter);
  const isStale = filter !== deferredFilter;

  return (
    <section style={sectionStyle}>
      <h2 style={headingStyle}>useDeferredValue - Filtering planets</h2>
      <p style={{ fontSize: '13px', opacity: 0.7, marginBottom: '12px' }}>
        The list renders with a delayed filter value.
      </p>
      <input
        value={filter}
        onChange={(e) => setFilter(e.target.value)}
        placeholder="Filter planets..."
        style={inputStyle}
      />
      <div style={{ opacity: isStale ? 0.5 : 1, transition: 'opacity 0.3s' }}>
        <HeavyPlanetList filter={deferredFilter} />
      </div>
    </section>
  );
}

// --- SECTION 3: Suspense with lazy loading ---
const StarMap = lazy(() => new Promise(resolve => {
  setTimeout(() => {
    resolve({
      default: () => (
        <div style={{ padding: '20px', background: '#0d1b2a', borderRadius: '8px' }}>
          <h3 style={{ color: '#00d4ff' }}>Star Map</h3>
          <p>Displaying 1,247 star systems in sector Alpha...</p>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '8px', marginTop: '12px' }}>
            {['Sirius', 'Vega', 'Altair', 'Rigel', 'Betelgeuse', 'Polaris', 'Deneb', 'Capella'].map(star => (
              <div key={star} style={{ padding: '8px', background: '#1a2a3a', borderRadius: '4px', textAlign: 'center', fontSize: '12px' }}>
                {star}
              </div>
            ))}
          </div>
        </div>
      )
    });
  }, 1500);
}));

const MissionLog = lazy(() => new Promise(resolve => {
  setTimeout(() => {
    resolve({
      default: () => (
        <div style={{ padding: '20px', background: '#0d1b2a', borderRadius: '8px' }}>
          <h3 style={{ color: '#ffd700' }}>Mission Log</h3>
          {['Mission Alpha started', 'Mars orbit achieved', 'Probe sent to Europa', 'Contact with base lost', 'Systems restored'].map((log, i) => (
            <p key={i} style={{ fontSize: '13px', padding: '4px 0', borderBottom: '1px solid #1a2a3a' }}>
              [{5 - i}h ago] {log}
            </p>
          ))}
        </div>
      )
    });
  }, 2000);
}));

function SuspenseDemo() {
  const [view, setView] = useState('none');

  return (
    <section style={sectionStyle}>
      <h2 style={headingStyle}>Suspense - Lazy loading</h2>
      <p style={{ fontSize: '13px', opacity: 0.7, marginBottom: '12px' }}>
        Components loaded dynamically with Suspense fallback.
      </p>
      <div style={{ display: 'flex', gap: '8px', marginBottom: '12px' }}>
        <button onClick={() => setView('map')} style={view === 'map' ? btnActiveStyle : btnStyle}>
          Star Map
        </button>
        <button onClick={() => setView('log')} style={view === 'log' ? btnActiveStyle : btnStyle}>
          Mission Log
        </button>
      </div>
      <Suspense fallback={
        <div style={{ padding: '20px', textAlign: 'center', color: '#ffd700' }}>
          Loading module...
        </div>
      }>
        {view === 'map' && <StarMap />}
        {view === 'log' && <MissionLog />}
      </Suspense>
    </section>
  );
}

// --- SECTION 4: Tabs with useTransition ---
function TabsDemo() {
  const [activeTab, setActiveTab] = useState('overview');
  const [isPending, startTransition] = useTransition();

  const tabs = [
    { id: 'overview', label: 'Overview', content: 'Mission status: Active. All systems nominal.' },
    { id: 'crew', label: 'Crew', content: 'Crew: 6 members. Captain Ra, 2 pilots, 2 engineers, 1 scientist.' },
    { id: 'systems', label: 'Systems', content: 'Engines: 85%. Oxygen: 97%. Shields: 100%. Communications: Active.' },
  ];

  const switchTab = (tabId) => {
    startTransition(() => {
      setActiveTab(tabId);
    });
  };

  const activeContent = tabs.find(t => t.id === activeTab);

  return (
    <section style={sectionStyle}>
      <h2 style={headingStyle}>useTransition - Tabs</h2>
      <div style={{ display: 'flex', gap: '4px', marginBottom: '12px' }}>
        {tabs.map(tab => (
          <button
            key={tab.id}
            onClick={() => switchTab(tab.id)}
            style={{
              ...btnStyle,
              background: activeTab === tab.id ? '#00d4ff' : '#1a2a3a',
              color: activeTab === tab.id ? '#000' : '#fff',
              opacity: isPending ? 0.7 : 1,
            }}
          >
            {tab.label}
          </button>
        ))}
      </div>
      <div style={{ padding: '12px', background: '#0d1b2a', borderRadius: '6px' }}>
        {isPending ? (
          <p style={{ color: '#ffd700' }}>Switching...</p>
        ) : (
          <p>{activeContent?.content}</p>
        )}
      </div>
    </section>
  );
}

// --- Style ---
const sectionStyle = {
  marginBottom: '24px',
  padding: '16px',
  background: 'rgba(255,255,255,0.03)',
  borderRadius: '12px',
  border: '1px solid rgba(255,255,255,0.08)',
};
const headingStyle = { color: '#00d4ff', marginBottom: '8px', fontSize: '16px' };
const inputStyle = {
  width: '100%',
  padding: '10px',
  background: '#0d1b2a',
  border: '1px solid #1a3a5c',
  borderRadius: '6px',
  color: '#fff',
  fontSize: '14px',
  marginBottom: '12px',
  boxSizing: 'border-box',
};
const listItemStyle = {
  padding: '6px 10px',
  background: '#0d1b2a',
  marginBottom: '4px',
  borderRadius: '4px',
  fontSize: '13px',
};
const btnStyle = {
  padding: '8px 14px',
  background: '#1a2a3a',
  border: 'none',
  borderRadius: '6px',
  color: '#fff',
  cursor: 'pointer',
  fontSize: '13px',
};
const btnActiveStyle = {
  ...btnStyle,
  background: '#00d4ff',
  color: '#000',
};

// --- App ---
function App() {
  return (
    <div style={{ padding: '20px', background: '#0a0e1a', color: '#e0e0e0', minHeight: '100vh', fontFamily: 'system-ui' }}>
      <h1 style={{ color: '#ffd700', textAlign: 'center', marginBottom: '24px' }}>
        Concurrent Mode and Suspense
      </h1>
      <GalaxySearch />
      <DeferredValueDemo />
      <SuspenseDemo />
      <TabsDemo />
    </div>
  );
}

export default App;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. When is it worth using a Higher-Order Component (HOC) instead of a custom hook?

Hands-on tasks in the game

  • Horizontal ordering

    Arrange the syntax for using startTransition to mark a less urgent update:

  • Code editor

    System Compound Components

  • Vertical ordering

    Arrange the steps for creating a custom hook in React:

  • Code editor

    State machine with Context API

  1. Put in orderstartTransition in React
  2. QuestionIntroduction: When to Use HOC vs Custom Hooks
  3. Coding taskIntroduction: Practice: Compound Components
  4. Put in orderSteps for Creating a Custom Hook
  5. Coding taskPractice: State Machine

Useful articles