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

Performance Profiling

11 min read ยท
In this lesson7

Our cosmic journey through React is nearing its end, but before we set off for further explorations, we need to make sure our spaceship is running at maximum capacity. In this module, we will focus on profiling the performance of React applications - that is, identifying and analyzing "bottlenecks" in our code.

What is performance profiling?

Performance profiling is the process of identifying places in an application that consume the most resources (CPU time, memory) and may lead to slow user interface behavior. It is like diagnosing the engines of a spaceship to check which parts are not running efficiently and can be optimized.

In the context of React applications, profiling allows you to:

  • Identify components that render too often
  • Locate long-running operations
  • Understand rendering patterns
  • Detect unnecessary state updates
  • Point out areas requiring optimization

React profiling tools

1. React DevTools Profiler

React DevTools is a browser extension that allows analyzing the performance of React applications. It includes a "Profiler" tab, which is the simplest and most powerful tool for profiling React applications.

How to use React DevTools Profiler:

  1. Installing React DevTools

  2. Starting profiling:

    • Open browser developer tools
    • Go to the "Profiler" tab in React DevTools
    • Click the record button (red circle)
    • Perform actions in the application you want to profile
    • Stop recording
  3. Analyzing results:

    • Flame Chart - shows the hierarchy of rendered components and their rendering time
    • Ranked Chart - sorts components by rendering time
    • Component Chart - shows which components were re-rendered in each update

Interpreting colors in the Profiler:

  • Gray - the component did not render during the update
  • Yellow/Orange/Red - the component rendered, and the color indicates how long it took (the more red, the longer)
  • Black - the component was the cause of the update (e.g., by changing state)

2. Chrome Performance Panel

Chrome DevTools includes a Performance panel that allows for more general page performance profiling:

  1. Starting profiling:

    • Open DevTools in Chrome (F12)
    • Go to the "Performance" tab
    • Click the record button
    • Perform actions in the application
    • Stop recording
  2. Analyze results:

    • Main - shows activity on the main thread (where most JS work happens)
    • Frames - shows frames per second (FPS)
    • Network - shows network activity
    • Memory - shows memory usage

This panel is particularly useful for identifying:

  • Long-running scripts blocking the main thread
  • Excessive DOM operations
  • Rendering performance issues

3. Built-in React profiling API

React provides a built-in API for profiling in development mode:

// Import the Profiler component
import { Profiler } from 'react';

// Callback function called after rendering
function onRenderCallback(
  id, // identifier of the profiled component tree
  phase, // "mount" (first render) or "update" (re-render)
  actualDuration, // time spent rendering
  baseDuration, // estimated render time of the entire subtree without optimizations
  startTime, // when React started rendering
  commitTime, // when React finished rendering
  interactions // set of "interactions" tracked for this render
) {
  console.log({
    id,
    phase,
    actualDuration,
    baseDuration,
    startTime,
    commitTime
  });
}

// Using the Profiler component in the application
function App() {
  return (
    <Profiler id="MissionControl" onRender={onRenderCallback}>
      <MissionControl />
    </Profiler>
  );
}

You can nest Profiler components to profile different parts of the application:

function Dashboard() {
  return (
    <Profiler id="Dashboard" onRender={onRenderCallback}>
      <h1>Mission Control Panel</h1>

      <Profiler id="Navigation" onRender={onRenderCallback}>
        <Navigation />
      </Profiler>

      <Profiler id="Stats" onRender={onRenderCallback}>
        <MissionStats />
      </Profiler>

      <Profiler id="Crew" onRender={onRenderCallback}>
        <CrewStatus />
      </Profiler>
    </Profiler>
  );
}

This method of profiling is particularly useful when:

  • You want to collect performance data in a test environment
  • You have specific components you want to monitor
  • You want to automate performance data collection

Common performance issues and how to profile them

1. Components rendering too frequently

Problem: Components re-render even when their data hasn't changed.

How to profile:

  • Use React DevTools Profiler to see which components render too often
  • Check if parent components are causing unnecessary child renders

Example of the problem:

function ParentComponent() {
  const [count, setCount] = useState(0);

  // This function is created anew on every render
  const handleClick = () => {
    console.log('Button clicked');
  };

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>
        Increase counter: {count}
      </button>

      {/* ChildComponent will re-render on every count change,
          even though handleClick has the same functionality */}
      <ChildComponent onClick={handleClick} />
    </div>
  );
}

Solution:

function ParentComponent() {
  const [count, setCount] = useState(0);

  // Function memoization prevents creating a new reference on every render
  const handleClick = useCallback(() => {
    console.log('Button clicked');
  }, []);

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>
        Increase counter: {count}
      </button>

      {/* ChildComponent wrapped in React.memo won't re-render
          when its props don't change */}
      <MemoizedChildComponent onClick={handleClick} />
    </div>
  );
}

const MemoizedChildComponent = React.memo(ChildComponent);

2. Heavy computations during rendering

Problem: Performing complex calculations during rendering causes UI delays.

How to profile:

  • Observe in React DevTools Profiler which components have the longest rendering time
  • Use Chrome Performance Panel to see long JavaScript tasks

Example of the problem:

function DataAnalytics({ data }) {
  // Heavy computations performed on every render
  const processedData = processLargeDataset(data);
  const statistics = calculateStatistics(processedData);

  return (
    <div>
      <h2>Mission Data Analysis</h2>
      <DataVisualisation stats={statistics} />
    </div>
  );
}

Solution:

function DataAnalytics({ data }) {
  // Memoizing heavy computations - they only run when data changes
  const processedData = useMemo(() => {
    return processLargeDataset(data);
  }, [data]);

  const statistics = useMemo(() => {
    return calculateStatistics(processedData);
  }, [processedData]);

  return (
    <div>
      <h2>Mission Data Analysis</h2>
      <DataVisualisation stats={statistics} />
    </div>
  );
}

3. Excessive state updates

Problem: Too frequent state updates cause cascading re-renders.

How to profile:

  • In React DevTools Profiler, find components marked in black (update initiators)
  • Observe update patterns - are some components updating in groups?

Example of the problem:

function SpaceshipSensors() {
  const [temperature, setTemperature] = useState(0);
  const [pressure, setPressure] = useState(0);
  const [oxygen, setOxygen] = useState(0);
  const [radiation, setRadiation] = useState(0);

  // Fetching sensor data every 100ms
  useEffect(() => {
    const interval = setInterval(() => {
      // Each update causes a separate render
      setTemperature(getTemperature());
      setPressure(getPressure());
      setOxygen(getOxygen());
      setRadiation(getRadiation());
    }, 100);

    return () => clearInterval(interval);
  }, []);

  return (
    <div>
      <h2>Sensor Readings</h2>
      <p>Temperature: {temperature}ยฐC</p>
      <p>Pressure: {pressure} hPa</p>
      <p>Oxygen level: {oxygen}%</p>
      <p>Radiation level: {radiation} ฮผSv/h</p>
    </div>
  );
}

Solution:

function SpaceshipSensors() {
  // Storing related data together in a single state object
  const [sensorData, setSensorData] = useState({
    temperature: 0,
    pressure: 0,
    oxygen: 0,
    radiation: 0
  });

  useEffect(() => {
    const interval = setInterval(() => {
      // One state update instead of four
      setSensorData({
        temperature: getTemperature(),
        pressure: getPressure(),
        oxygen: getOxygen(),
        radiation: getRadiation()
      });
    }, 100);

    return () => clearInterval(interval);
  }, []);

  return (
    <div>
      <h2>Sensor Readings</h2>
      <p>Temperature: {sensorData.temperature}ยฐC</p>
      <p>Pressure: {sensorData.pressure} hPa</p>
      <p>Oxygen level: {sensorData.oxygen}%</p>
      <p>Radiation level: {sensorData.radiation} ฮผSv/h</p>
    </div>
  );
}

4. Large lists and data visualizations

Problem: Rendering long lists or complex visualizations can slow down the interface.

How to profile:

  • Use React DevTools Profiler to identify list components that take a long time to render
  • Check how often individual list items render

Example of using React DevTools to profile list performance:

  1. Start profiling
  2. Scroll the list to see how the application responds
  3. Stop profiling
  4. Check which components have the longest rendering time in the ranked chart

Solution:

  • List virtualization (React Window, React Virtualized)
  • Memoizing list items
  • Pagination instead of displaying all elements at once

Advanced profiling techniques

1. User Timing API

The Browser Performance API allows creating custom time markers:

function ExpensiveComponent({ data }) {
  useEffect(() => {
    // Start measurement
    performance.mark('expensive-calculation-start');

    // Perform expensive calculations
    const result = performExpensiveCalculation(data);

    // End measurement
    performance.mark('expensive-calculation-end');

    // Create measurement between markers
    performance.measure(
      'expensive-calculation',
      'expensive-calculation-start',
      'expensive-calculation-end'
    );

    // Log results
    console.log(performance.getEntriesByName('expensive-calculation'));
  }, [data]);

  //
}

These markers will be visible in the Performance panel in Chrome DevTools.

2. Production performance monitoring

For monitoring performance in production, you can use:

  • Web Vitals - a Google library for measuring key performance indicators
  • New Relic, Datadog, Sentry - APM (Application Performance Monitoring) tools
  • Custom solutions using the Performance API and Profiler API

Example of collecting data from React Profiler and sending it to a server:

function onRenderCallback(id, phase, actualDuration, baseDuration, startTime, commitTime) {
  // We only collect data from the update phase that takes longer than 10ms
  if (phase === 'update' && actualDuration > 10) {
    sendToAnalyticsServer({
      componentId: id,
      renderTime: actualDuration,
      timestamp: Date.now()
    });
  }
}

function App() {
  return (
    <Profiler id="App" onRender={onRenderCallback}>
      <AppContent />
    </Profiler>
  );
}

Case study: Profiling and optimizing a React application

Let's analyze the process of profiling and optimizing the performance of a React application using the example of a space mission control panel:

Step 1: Identifying the problem

Users report that the control panel is slow, especially when displaying telemetry data and the event list.

Step 2: Profiling the application

We use React DevTools Profiler to identify the source of the problem:

  1. We record a session during normal panel use
  2. We analyze the results in the Profiler
  3. We discover that:
    • The TelemetryChart component renders very slowly (>100ms)
    • The EventsList component re-renders every time new telemetry data arrives
    • The calculateTrends function takes a lot of CPU time

Step 3: Optimization

Based on the profiling results, we introduce the following optimizations:

  1. Optimizing TelemetryChart:
// Before optimization
function TelemetryChart({ data }) {
  // Heavy data processing on every render
  const chartData = processChartData(data);

  return <LineChart data={chartData} />;
}

// After optimization
const TelemetryChart = React.memo(function TelemetryChart({ data }) {
  // Memoized data processing
  const chartData = useMemo(() => processChartData(data), [data]);

  return <LineChart data={chartData} />;
});
  1. Optimizing EventsList:
// Before optimization
function EventsList({ events }) {
  return (
    <div>
      {events.map(event => (
        <EventItem key={event.id} event={event} />
      ))}
    </div>
  );
}

// After optimization
const EventsList = React.memo(function EventsList({ events }) {
  return (
    <div>
      {events.map(event => (
        <MemoizedEventItem key={event.id} event={event} />
      ))}
    </div>
  );
});

const MemoizedEventItem = React.memo(EventItem);
  1. Moving heavy computations to a web worker:
// Before optimization
function MissionControlPanel({ telemetryData }) {
  const trends = calculateTrends(telemetryData);  // Blocks the main thread

  return (
    <div>
      <TrendsDisplay trends={trends} />
      {/* other components */}
    </div>
  );
}

// After optimization
function MissionControlPanel({ telemetryData }) {
  const [trends, setTrends] = useState(null);

  useEffect(() => {
    if (!telemetryData) return;

    // Create a web worker
    const worker = new Worker('./trendsWorker.js');

    // Listen for response
    worker.addEventListener('message', (event) => {
      setTrends(event.data);
      worker.terminate();
    });

    // Send data for processing
    worker.postMessage(telemetryData);
  }, [telemetryData]);

  return (
    <div>
      {trends ? <TrendsDisplay trends={trends} /> : <LoadingSpinner />}
      {/* other components */}
    </div>
  );
}

Step 4: Verifying optimizations

After introducing optimizations, we profile the application again:

  1. TelemetryChart rendering time dropped from >100ms to ~15ms
  2. The EventsList component no longer renders on telemetry data updates
  3. The main thread is no longer blocked by calculateTrends

Thanks to these optimizations, the user interface runs smoothly, and the control panel responds immediately to user interactions.

Best practices for profiling

  1. Profile in a production-like environment

    • Run the application in production mode (npm run build and serve the built files)
    • Test on devices similar to those used by users
  2. Establish baselines

    • Measure performance before and after optimizations
    • Set specific performance goals (e.g., first render time < 2s)
  3. Profile regularly

    • Include profiling in the application development cycle
    • Monitor performance after introducing major changes
  4. Focus on user perception

    • Prioritize optimizations that have the greatest impact on perceived performance
    • Remember key Web Vitals metrics (LCP, FID, CLS)
  5. Document profiling results

    • Record performance data before and after optimizations
    • Share knowledge and optimization techniques with the team

Summary

Performance profiling is an essential element of creating high-quality React applications. Just as space engineers monitor every aspect of a ship's operation, we should continuously analyze the performance of our applications to ensure users have a smooth and responsive experience.

Key points to remember:

  1. Use the right tools - React DevTools Profiler, Chrome Performance Panel
  2. Identify bottlenecks - find components that render too often or too long
  3. Apply appropriate optimization techniques - memoization, avoiding unnecessary renders, list virtualization
  4. Measure the effectiveness of optimizations - compare performance before and after changes
  5. Optimize in moderation - remember that premature optimization can lead to overly complicated code

With these profiling techniques and tools, you will be able to create performant React applications that provide an excellent experience for users, even in the most complex cosmic control panel interfaces.

Code for this lesson: App.jsx
import React, { useState, useMemo, useCallback, useEffect, useRef, Profiler } from 'react';

// ============================================
// REACT PERFORMANCE PROFILING
// ============================================
// This example demonstrates optimization techniques
// and profiling of React components.

// --- Profiling callback ---
function onRenderCallback(id, phase, actualDuration, baseDuration) {
  console.log(
    `[Profiler] ${id} | phase: ${phase} | actual: ${actualDuration.toFixed(2)}ms | base: ${baseDuration.toFixed(2)}ms`
  );
}

// --- Simulating a heavy computation ---
function expensiveCalculation(items) {
  let result = 0;
  for (let i = 0; i < items.length; i++) {
    for (let j = 0; j < 1000; j++) {
      result += Math.sqrt(items[i].value * j + 1);
    }
  }
  return result.toFixed(2);
}

// --- Component WITHOUT optimization ---
function UnoptimizedChild({ label, onClick }) {
  const renderCount = useRef(0);
  renderCount.current += 1;

  return (
    <div style={childStyle}>
      <span>{label}</span>
      <span style={renderBadge}>{renderCount.current}x rendered</span>
      <button onClick={onClick} style={btnStyle}>Click</button>
    </div>
  );
}

// --- Component WITH optimization (React.memo) ---
const OptimizedChild = React.memo(function OptimizedChild({ label, onClick }) {
  const renderCount = useRef(0);
  renderCount.current += 1;

  return (
    <div style={{ ...childStyle, borderColor: '#4CAF50' }}>
      <span>{label}</span>
      <span style={{ ...renderBadge, background: '#4CAF50' }}>{renderCount.current}x rendered</span>
      <button onClick={onClick} style={{ ...btnStyle, background: '#4CAF50' }}>Click</button>
    </div>
  );
});

// --- List component with virtualization (simplified) ---
function VirtualizedList({ items, itemHeight = 40, containerHeight = 200 }) {
  const [scrollTop, setScrollTop] = useState(0);
  const containerRef = useRef(null);

  const visibleStart = Math.floor(scrollTop / itemHeight);
  const visibleCount = Math.ceil(containerHeight / itemHeight) + 1;
  const visibleItems = items.slice(visibleStart, visibleStart + visibleCount);

  return (
    <div
      ref={containerRef}
      onScroll={(e) => setScrollTop(e.target.scrollTop)}
      style={{
        height: containerHeight, overflow: 'auto',
        background: '#0d1b2a', borderRadius: '8px', border: '1px solid #2a3f5f',
      }}
    >
      <div style={{ height: items.length * itemHeight, position: 'relative' }}>
        {visibleItems.map((item, i) => (
          <div
            key={item.id}
            style={{
              position: 'absolute', top: (visibleStart + i) * itemHeight,
              height: itemHeight, width: '100%', padding: '8px 12px',
              boxSizing: 'border-box', borderBottom: '1px solid #1b2838',
              color: '#e0e1dd', display: 'flex', alignItems: 'center',
            }}
          >
            {item.name} - value: {item.value}
          </div>
        ))}
      </div>
    </div>
  );
}

// --- Main application ---
function App() {
  const [count, setCount] = useState(0);
  const [filterText, setFilterText] = useState('');
  const [showOptimized, setShowOptimized] = useState(false);

  // We generate a list of 500 elements
  const largeList = useMemo(() => {
    return Array.from({ length: 500 }, (_, i) => ({
      id: i,
      name: `Mission #${i + 1}`,
      value: Math.floor(Math.random() * 1000),
    }));
  }, []);

  // Filtering with useMemo - calculations run only when data changes
  const filteredItems = useMemo(() => {
    return largeList.filter((item) =>
      item.name.toLowerCase().includes(filterText.toLowerCase())
    );
  }, [largeList, filterText]);

  // Heavy computation with memoization
  const expensiveResult = useMemo(() => {
    return expensiveCalculation(filteredItems.slice(0, 50));
  }, [filteredItems]);

  // Callback WITHOUT memoization (new reference on every render)
  const handleClickUnoptimized = () => {
    console.log('Click without memoization');
  };

  // Callback WITH memoization (stable reference)
  const handleClickOptimized = useCallback(() => {
    console.log('Click with useCallback');
  }, []);

  return (
    <div style={appStyle}>
      <h1 style={{ color: '#ffd700', textAlign: 'center', marginBottom: '8px' }}>
        React Performance Profiling
      </h1>
      <p style={{ textAlign: 'center', color: '#aaa', marginBottom: '20px' }}>
        Open the browser console to see the Profiler logs
      </p>

      {/* Section 1: React.memo + useCallback */}
      <Profiler id="MemoDemo" onRender={onRenderCallback}>
        <div style={sectionStyle}>
          <h2 style={headingStyle}>React.memo + useCallback</h2>
          <p style={{ color: '#aaa', marginBottom: '12px' }}>
            Click "+1" and observe which component re-renders.
          </p>
          <div style={{ textAlign: 'center', marginBottom: '16px' }}>
            <span style={{ fontSize: '24px', marginRight: '12px' }}>Counter: {count}</span>
            <button onClick={() => setCount((c) => c + 1)} style={btnAccent}>+1</button>
          </div>

          <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
            <div style={{ flex: 1, minWidth: '220px' }}>
              <h3 style={{ color: '#ff6b6b' }}>Without optimization</h3>
              <UnoptimizedChild
                label="Component A"
                onClick={handleClickUnoptimized}
              />
            </div>
            <div style={{ flex: 1, minWidth: '220px' }}>
              <h3 style={{ color: '#4CAF50' }}>With React.memo + useCallback</h3>
              <OptimizedChild
                label="Component B"
                onClick={handleClickOptimized}
              />
            </div>
          </div>
        </div>
      </Profiler>

      {/* Section 2: useMemo on heavy computations */}
      <Profiler id="UseMemoDemo" onRender={onRenderCallback}>
        <div style={sectionStyle}>
          <h2 style={headingStyle}>useMemo - heavy computations</h2>
          <p style={{ color: '#aaa', marginBottom: '12px' }}>
            Filtering and calculations are memoized - changing the filter recalculates the result.
          </p>
          <input
            value={filterText}
            onChange={(e) => setFilterText(e.target.value)}
            placeholder="Filter missions..."
            style={inputStyle}
          />
          <p style={{ margin: '8px 0', color: '#ffd700' }}>
            Calculation result: {expensiveResult} | Found: {filteredItems.length} missions
          </p>
        </div>
      </Profiler>

      {/* Section 3: List virtualization */}
      <Profiler id="VirtualizedListDemo" onRender={onRenderCallback}>
        <div style={sectionStyle}>
          <h2 style={headingStyle}>List virtualization (500 elements)</h2>
          <p style={{ color: '#aaa', marginBottom: '12px' }}>
            Only visible elements are rendered - scroll the list.
          </p>
          <label style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px', cursor: 'pointer' }}>
            <input
              type="checkbox"
              checked={showOptimized}
              onChange={() => setShowOptimized(!showOptimized)}
            />
            Show virtualized list
          </label>

          {showOptimized ? (
            <VirtualizedList items={filteredItems} />
          ) : (
            <div style={{
              height: 200, overflow: 'auto', background: '#0d1b2a',
              borderRadius: '8px', border: '1px solid #2a3f5f',
            }}>
              {filteredItems.map((item) => (
                <div key={item.id} style={{
                  padding: '8px 12px', borderBottom: '1px solid #1b2838',
                  color: '#e0e1dd',
                }}>
                  {item.name} - value: {item.value}
                </div>
              ))}
            </div>
          )}
        </div>
      </Profiler>

      {/* TODO: Add a section comparing the performance
          of two approaches to state updates:
          1. Multiple separate useState calls (temperature, pressure, oxygen)
          2. One useState with an object { temperature, pressure, oxygen }
          Use the Profiler component to measure the differences. */}
    </div>
  );
}

// --- Style ---
const appStyle = {
  background: '#0d1b2a', minHeight: '100vh', padding: '20px',
  fontFamily: 'Arial, sans-serif', color: '#e0e1dd',
};
const sectionStyle = {
  background: '#1b2838', borderRadius: '12px', padding: '20px',
  maxWidth: '700px', margin: '16px auto', border: '1px solid #2a3f5f',
};
const headingStyle = { color: '#00d4ff', marginBottom: '8px' };
const childStyle = {
  display: 'flex', alignItems: 'center', gap: '10px',
  padding: '10px', background: '#0d1b2a', borderRadius: '8px',
  border: '1px solid #ff6b6b', marginBottom: '8px',
};
const renderBadge = {
  background: '#ff6b6b', color: '#fff', padding: '2px 8px',
  borderRadius: '12px', fontSize: '12px',
};
const btnStyle = {
  marginLeft: 'auto', padding: '6px 14px', background: '#ff6b6b',
  color: '#fff', border: 'none', borderRadius: '6px', cursor: 'pointer',
};
const btnAccent = {
  padding: '8px 20px', background: '#ffd700', color: '#000',
  border: 'none', borderRadius: '8px', cursor: 'pointer', fontWeight: 'bold',
};
const inputStyle = {
  width: '100%', padding: '8px 12px', background: '#0d1b2a',
  border: '1px solid #2a3f5f', borderRadius: '6px', color: '#e0e1dd',
  fontSize: '14px', boxSizing: 'border-box',
};

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. What does React.memo() do and when should you use it?

  2. 2. What is React Profiler in React DevTools used for?

Hands-on tasks in the game

  • Code editor

    Dynamic Module Loading

  • Horizontal ordering

    Arrange the Suspense syntax with fallback UI:

  • Vertical ordering

    Arrange testing strategies by priority:

  • Code editor

    Custom hook useForm with validation

  1. QuestionReact.memo for Optimization
  2. QuestionReact Profiler
  3. Coding taskPractice: Code Splitting
  4. Put in orderCode Splitting with React.lazy
  5. Put in orderTesting Strategy Priorities
  6. Coding taskPractice: useForm Hook with Validation

Useful articles