Back to journal

    Developer journal

    React Performance Optimization: Practical Techniques for Faster Applications

    Learn practical React performance optimization techniques, from preventing unnecessary renders and improving component architecture to code splitting, list virtualization, and measuring Core Web Vitals.

    26 min read54 sections
    React Performance Optimization: Practical Techniques for Faster Applications article cover
    In this article54 sectionsBrowse sections
    26 min read · 5,083 words

    React Performance Optimization: Practical Techniques for Faster Applications

    React makes it easier to build complex user interfaces using reusable components and declarative rendering. However, as an application grows, performance problems can become noticeable.

    A dashboard with hundreds of records might become sluggish. A search field might lag while typing. A page may take several seconds to load because the initial JavaScript bundle is too large. Even a well-designed application can feel slow when unnecessary work happens during rendering.

    The solution is not to add useMemo, useCallback, and React.memo to every component.

    Effective React performance optimization starts with identifying the actual bottleneck, understanding why it happens, and applying the smallest useful improvement.

    In this guide, we will explore practical techniques for optimizing React applications, including component rendering, state management, memoization, code splitting, large lists, network requests, and Core Web Vitals.

    1. Understanding React Rendering

    Before optimizing a React application, it is important to understand how rendering works.

    React generally performs three steps when updating the interface:

    1. Trigger: A state update, parent render, or other React update schedules rendering.
    2. Render: React calls components to calculate the next UI.
    3. Commit: React applies the necessary changes to the DOM.

    A component rendering does not necessarily mean that the browser will update every DOM element inside it.

    React compares the previous and next results and commits the necessary changes.

    For example:

    import { useState } from 'react'
    
    function Counter() {
      const [count, setCount] = useState(0)
    
      console.log('Counter rendered')
    
      return (
        <button onClick={() => setCount(count + 1)}>
          Count: {count}
        </button>
      )
    }
    
    export default Counter
    

    Every time the button is clicked, the state changes and React renders the component again.

    This is expected behavior.

    The problem occurs when an update causes large parts of the application to perform expensive calculations or render work that could have been avoided.

    It is important to distinguish between:

    • A component function being called.
    • React committing DOM changes.
    • The browser performing layout, painting, and compositing.

    These are related but different operations.

    Understanding the distinction helps prevent incorrect assumptions about React performance.

    Reference: React — Render and Commit.

    2. Measure Before Optimizing

    One of the biggest mistakes developers make is optimizing code based on assumptions.

    For example, a developer might see a component rendering frequently and immediately wrap it in React.memo.

    But frequent rendering is not necessarily expensive.

    A component that renders a small heading or button may have practically no measurable performance impact.

    Instead, identify what is actually causing the delay.

    2.1 React Developer Tools Profiler

    React Developer Tools provides a Profiler that helps identify rendering activity.

    Install the React Developer Tools browser extension and open the Profiler tab.

    You can:

    • Record interactions.
    • Inspect which components rendered.
    • Identify components with expensive rendering work.
    • Compare rendering durations.
    • Find unnecessary updates.

    For example, consider a dashboard with a search field and a table containing hundreds of rows.

    If typing into the search field causes the entire dashboard to perform expensive work, the Profiler can help identify the components involved.

    2.2 React Profiler Component

    React also provides a programmatic Profiler component.

    import { Profiler } from 'react'
    
    function onRender(
      id,
      phase,
      actualDuration,
      baseDuration
    ) {
      console.log({
        id,
        phase,
        actualDuration,
        baseDuration,
      })
    }
    
    function App() {
      return (
        <Profiler id="Dashboard" onRender={onRender}>
          <Dashboard />
        </Profiler>
      )
    }
    

    The important values include:

    • id: Identifier of the profiled subtree.
    • phase: Whether the commit represents a mount or update.
    • actualDuration: Time spent rendering the profiled subtree for the current update.
    • baseDuration: An estimate of the time required to render the entire subtree without optimizations.

    Use profiling to investigate performance problems rather than collecting measurements without a clear purpose.

    Note that development measurements and production behavior can differ. React DevTools profiling and browser performance measurements should be used together when investigating real-world problems.

    2.3 Chrome Performance Panel

    React Profiler focuses on React rendering.

    Chrome DevTools Performance provides a broader view of browser activity, including:

    • JavaScript execution.
    • Long tasks.
    • Layout and painting.
    • Network activity.
    • Main-thread blocking.
    • Interaction responsiveness.

    A slow React application is not always caused by React itself. Large images, expensive JavaScript, synchronous third-party scripts, and layout recalculations can also be responsible.

    3. Avoid Unnecessary State Updates and Effects

    A good component architecture can eliminate many performance problems before memoization is necessary.

    One common mistake is storing values in state even when they can be calculated from existing state or props.

    Consider this example:

    import { useEffect, useState } from 'react'
    
    function UserProfile({ firstName, lastName }) {
      const [fullName, setFullName] = useState('')
    
      useEffect(() => {
        setFullName(`${firstName} ${lastName}`)
      }, [firstName, lastName])
    
      return <h2>{fullName}</h2>
    }
    

    This implementation introduces an unnecessary state variable and an additional render cycle.

    Instead:

    function UserProfile({ firstName, lastName }) {
      const fullName = `${firstName} ${lastName}`
    
      return <h2>{fullName}</h2>
    }
    

    The value is calculated directly during rendering.

    This approach:

    • Removes redundant state.
    • Avoids an unnecessary Effect.
    • Reduces extra rendering work.
    • Keeps the component easier to understand.

    The same principle applies to filtering and transforming data.

    Avoid using Effects to synchronize values that can be derived directly from existing props or state.

    Reference: React — You Might Not Need an Effect.

    4. Optimize Component Architecture

    Component architecture has a significant impact on React performance.

    A poorly structured application can cause unrelated components to update whenever shared state changes.

    Consider a dashboard:

    function Dashboard() {
      const [search, setSearch] = useState('')
      const [theme, setTheme] = useState('light')
      const [notifications, setNotifications] = useState([])
    
      return (
        <div>
          <SearchInput
            search={search}
            setSearch={setSearch}
          />
    
          <UserTable />
    
          <ThemeSelector
            theme={theme}
            setTheme={setTheme}
          />
    
          <NotificationPanel
            notifications={notifications}
          />
        </div>
      )
    }
    

    All these states live in the same parent component.

    When the search input changes, the parent renders again. Its child components are also considered for rendering.

    For a small application, this might not matter. But in a large dashboard, unnecessary work can accumulate.

    4.1 Keep State Close to Where It Is Used

    Move local state into the component that actually needs it.

    function SearchInput() {
      const [search, setSearch] = useState('')
    
      return (
        <input
          value={search}
          onChange={(event) => setSearch(event.target.value)}
          placeholder="Search users..."
        />
      )
    }
    
    function Dashboard() {
      return (
        <div>
          <SearchInput />
          <UserTable />
          <ThemeSelector />
          <NotificationPanel />
        </div>
      )
    }
    

    Now the search input manages its own state.

    Changing the search value does not automatically require the dashboard parent to render again.

    If the table needs the search value, pass it through an appropriate shared state boundary or use a data-fetching mechanism designed for the task.

    The principle is not to avoid shared state entirely. It is to avoid lifting transient state higher than necessary.

    4.2 Split Large Components

    A component that handles routing, data fetching, filtering, forms, dialogs, and tables can become difficult to optimize.

    Break it into smaller components with clear responsibilities.

    Dashboard/
      Dashboard.jsx
      components/
        DashboardHeader.jsx
        SearchBar.jsx
        StatisticsCards.jsx
        UserTable.jsx
        UserTableRow.jsx
        UserFilters.jsx
        EditUserDialog.jsx
      hooks/
        useUsers.js
        useUserFilters.js
    

    This structure improves maintainability and makes it easier to isolate expensive parts of the interface.

    However, creating hundreds of tiny components without a meaningful boundary can also make the codebase harder to maintain.

    Use component boundaries to represent responsibilities, reusable UI, and independent state—not simply to reduce file length.

    5. Understanding React.memo

    React.memo is a higher-order component that can skip rendering a component when its props have not changed according to its comparison rules.

    Consider this example:

    import { memo, useState } from 'react'
    
    const UserCard = memo(function UserCard({ user }) {
      console.log('UserCard rendered')
    
      return (
        <div>
          <h3>{user.name}</h3>
          <p>{user.email}</p>
        </div>
      )
    })
    
    function App() {
      const [count, setCount] = useState(0)
    
      const user = {
        name: 'Robin',
        email: '[email protected]',
      }
    
      return (
        <>
          <button onClick={() => setCount(count + 1)}>
            Count: {count}
          </button>
    
          <UserCard user={user} />
        </>
      )
    }
    

    Although UserCard is memoized, it still renders whenever the parent renders.

    Why?

    Because the parent creates a new user object on every render.

    React compares object references, not the internal properties of ordinary objects.

    Fixing the Problem

    You can stabilize the object with useMemo:

    import { memo, useMemo, useState } from 'react'
    
    const UserCard = memo(function UserCard({ user }) {
      console.log('UserCard rendered')
    
      return (
        <div>
          <h3>{user.name}</h3>
          <p>{user.email}</p>
        </div>
      )
    })
    
    function App() {
      const [count, setCount] = useState(0)
    
      const user = useMemo(() => ({
        name: 'Robin',
        email: '[email protected]',
      }), [])
    
      return (
        <>
          <button onClick={() => setCount(count + 1)}>
            Count: {count}
          </button>
    
          <UserCard user={user} />
        </>
      )
    }
    

    Now the object reference remains stable between renders.

    UserCard can skip rendering when its props have not changed.

    When Should You Use React.memo?

    Consider it when:

    • A component performs expensive rendering work.
    • It receives the same props across frequent parent updates.
    • Profiling shows that skipping its rendering work provides a measurable improvement.

    Avoid adding it to every component automatically.

    Memoization has its own costs and can make code more complicated.

    Also remember that React.memo does not prevent a component from rendering when its own state or consumed context changes.

    Reference: React — memo.

    6. Using useMemo for Expensive Calculations

    useMemo caches the result of a calculation between renders.

    Consider a large list of products.

    function ProductList({ products, search }) {
      const filteredProducts = products.filter((product) =>
        product.name.toLowerCase().includes(search.toLowerCase())
      )
    
      return (
        <div>
          {filteredProducts.map((product) => (
            <div key={product.id}>
              {product.name}
            </div>
          ))}
        </div>
      )
    }
    

    Filtering a small array is inexpensive.

    However, filtering a large dataset repeatedly can become noticeable.

    You can memoize the calculation:

    import { useMemo } from 'react'
    
    function ProductList({ products, search }) {
      const filteredProducts = useMemo(() => {
        const normalizedSearch = search.toLowerCase()
    
        return products.filter((product) =>
          product.name.toLowerCase().includes(normalizedSearch)
        )
      }, [products, search])
    
      return (
        <div>
          {filteredProducts.map((product) => (
            <div key={product.id}>
              {product.name}
            </div>
          ))}
        </div>
      )
    }
    

    React recalculates the filtered list when products or search changes.

    Otherwise, it can reuse the previously calculated result.

    When Is useMemo Useful?

    Use it when:

    • Calculations are genuinely expensive.
    • Large arrays need repeated filtering or sorting.
    • A stable object reference is needed for a memoized child.
    • A calculation is repeatedly performed during unrelated renders.

    Do not use it for every variable.

    For example:

    const total = price * quantity
    

    There is usually no reason to memoize such a simple calculation.

    A useful rule is to measure first and optimize only when the calculation meaningfully affects performance.

    Reference: React — useMemo.

    7. Using useCallback for Stable Function References

    JavaScript creates a new function object when a function expression is evaluated.

    This can affect memoized components when functions are passed as props.

    Consider:

    import { memo, useState } from 'react'
    
    const SaveButton = memo(function SaveButton({ onSave }) {
      console.log('SaveButton rendered')
    
      return (
        <button onClick={onSave}>
          Save
        </button>
      )
    })
    
    function Editor() {
      const [title, setTitle] = useState('Untitled')
    
      const handleSave = () => {
        console.log('Saving:', title)
      }
    
      return (
        <>
          <input
            value={title}
            onChange={(event) => setTitle(event.target.value)}
          />
    
          <SaveButton onSave={handleSave} />
        </>
      )
    }
    

    Whenever Editor renders, handleSave receives a new reference.

    Consequently, the memoized button may render again.

    You can use useCallback to cache the function reference:

    import { memo, useCallback, useState } from 'react'
    
    const SaveButton = memo(function SaveButton({ onSave }) {
      console.log('SaveButton rendered')
    
      return (
        <button onClick={onSave}>
          Save
        </button>
      )
    })
    
    function Editor() {
      const [title, setTitle] = useState('Untitled')
    
      const handleSave = useCallback(() => {
        console.log('Saving:', title)
      }, [title])
    
      return (
        <>
          <input
            value={title}
            onChange={(event) => setTitle(event.target.value)}
          />
    
          <SaveButton onSave={handleSave} />
        </>
      )
    }
    

    The function reference remains stable until its dependencies change.

    Avoid Incorrect Dependencies

    Every reactive value referenced inside a callback should be included in its dependency array.

    Missing dependencies can introduce stale-value bugs.

    For state updates that depend on the previous state, a functional update can sometimes avoid needing the current state as a dependency.

    const increment = useCallback(() => {
      setCount((previousCount) => previousCount + 1)
    }, [])
    

    Use useCallback when stable function identity provides a real benefit, such as when passing callbacks to memoized children or using them as dependencies.

    It is not necessary to wrap every event handler.

    Reference: React — useCallback.

    8. React Compiler and Automatic Memoization

    Modern React development also includes React Compiler, which can automatically optimize component rendering and memoize values and functions where appropriate.

    This changes how developers should think about manual memoization.

    Instead of automatically adding useMemo, useCallback, and React.memo everywhere, developers can use the compiler to handle many common memoization cases.

    However, React Compiler does not eliminate the need for good architecture or performance measurement.

    It cannot automatically solve every problem, such as:

    • Extremely large DOM trees.
    • Expensive network requests.
    • Huge images.
    • Poor database queries.
    • Excessive third-party scripts.
    • Inefficient algorithms.
    • Unnecessary application state updates.

    Compiler adoption also depends on project configuration and compatibility with the code being compiled.

    Before introducing it into an existing application, follow the official setup instructions and review compiler diagnostics.

    Reference: React Compiler.

    9. Avoid Unnecessary Context Re-Renders

    React Context is useful for sharing values across components without manually passing props through every level.

    However, context updates can cause all consumers of a context to render again.

    Consider:

    import { createContext, useState } from 'react'
    
    export const AppContext = createContext(null)
    
    function AppProvider({ children }) {
      const [user, setUser] = useState(null)
      const [theme, setTheme] = useState('light')
    
      const value = {
        user,
        setUser,
        theme,
        setTheme,
      }
    
      return (
        <AppContext.Provider value={value}>
          {children}
        </AppContext.Provider>
      )
    }
    

    Whenever the provider renders, the value object is recreated.

    Consumers may receive a different context value even when the actual data they need has not changed.

    Split Context by Responsibility

    Instead of putting unrelated application state into one large context, separate it.

    const UserContext = createContext(null)
    const ThemeContext = createContext(null)
    

    Now components can subscribe to the context they actually need.

    You can also stabilize provider values when appropriate.

    import { useMemo, useState } from 'react'
    
    function ThemeProvider({ children }) {
      const [theme, setTheme] = useState('light')
    
      const value = useMemo(() => ({
        theme,
        setTheme,
      }), [theme])
    
      return (
        <ThemeContext.Provider value={value}>
          {children}
        </ThemeContext.Provider>
      )
    }
    

    For larger applications, consider whether Context is the right state management solution for frequently changing data.

    Libraries designed for selective subscriptions can be useful when updates need more granular control.

    10. Optimize Large Lists with Virtualization

    Rendering thousands of DOM elements can make an application slow.

    Imagine a dashboard displaying 10,000 users.

    A basic implementation might look like this:

    function UserList({ users }) {
      return (
        <div>
          {users.map((user) => (
            <div key={user.id}>
              <h3>{user.name}</h3>
              <p>{user.email}</p>
            </div>
          ))}
        </div>
      )
    }
    

    Even if React handles the data efficiently, the browser still needs to manage all the resulting DOM elements.

    This can increase:

    • DOM memory usage.
    • Layout and paint work.
    • Initial rendering time.
    • Scrolling overhead.

    What Is Virtualization?

    Virtualization renders only the items currently visible in the viewport, plus a small overscan region.

    Instead of rendering 10,000 elements, the application might render only 20–40 at a time.

    Total items: 10,000
    
    +----------------------+
    | Item 1               |
    | Item 2               |
    | Item 3               |
    | ...                  |
    |                      |
    | Visible viewport     |
    |                      |
    | Item 20              |
    +----------------------+
    
    Only visible items and a small
    overscan region are rendered.
    

    A popular solution is TanStack Virtual.

    Install it:

    npm install @tanstack/react-virtual
    

    Example:

    import { useRef } from 'react'
    import { useVirtualizer } from '@tanstack/react-virtual'
    
    function UserList({ users }) {
      const parentRef = useRef(null)
    
      const virtualizer = useVirtualizer({
        count: users.length,
    
        getScrollElement: () => parentRef.current,
    
        estimateSize: () => 64,
    
        overscan: 8,
      })
    
      return (
        <div
          ref={parentRef}
          style={{
            height: '500px',
            overflow: 'auto',
          }}
        >
          <div
            style={{
              height: `${virtualizer.getTotalSize()}px`,
              position: 'relative',
            }}
          >
            {virtualizer.getVirtualItems().map((virtualRow) => {
              const user = users[virtualRow.index]
    
              return (
                <div
                  key={user.id}
                  style={{
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    width: '100%',
                    height: `${virtualRow.size}px`,
                    transform: `translateY(${virtualRow.start}px)`,
                  }}
                >
                  <h3>{user.name}</h3>
                  <p>{user.email}</p>
                </div>
              )
            })}
          </div>
        </div>
      )
    }
    

    This example assumes a fixed estimated row height. For variable-height content, use the virtualizer's measurement features and test scrolling behavior carefully.

    Virtualization is especially useful for:

    • Admin dashboards.
    • Large data tables.
    • Chat message histories.
    • Activity feeds.
    • Product catalogues.
    • Search result lists.

    It does not replace backend pagination. Loading and storing hundreds of thousands of records in the browser is still inefficient.

    References: TanStack Virtual.

    11. Optimize Search and Input Responsiveness

    Search fields can become slow when every keystroke triggers expensive filtering or rendering.

    One useful technique is debouncing.

    11.1 Debouncing

    Debouncing delays execution until the user stops triggering an event for a specified duration.

    A simple React hook:

    import { useEffect, useState } from 'react'
    
    function useDebounce(value, delay = 300) {
      const [debouncedValue, setDebouncedValue] = useState(value)
    
      useEffect(() => {
        const timer = setTimeout(() => {
          setDebouncedValue(value)
        }, delay)
    
        return () => clearTimeout(timer)
      }, [value, delay])
    
      return debouncedValue
    }
    

    Use it:

    function SearchUsers() {
      const [search, setSearch] = useState('')
    
      const debouncedSearch = useDebounce(search, 300)
    
      useEffect(() => {
        if (!debouncedSearch.trim()) {
          return
        }
    
        // Fetch matching users here.
      }, [debouncedSearch])
    
      return (
        <input
          value={search}
          onChange={(event) => setSearch(event.target.value)}
          placeholder="Search users..."
        />
      )
    }
    

    Now the search request is triggered after the user pauses typing.

    Remember that a production API search should also handle:

    • Request cancellation.
    • Race conditions between responses.
    • Loading and error states.
    • Pagination.
    • Server-side filtering.

    Debouncing reduces the number of requests, but it does not guarantee that the latest response arrives first.

    11.2 useDeferredValue

    React provides useDeferredValue to defer updating part of the UI when immediate updates are more important.

    import { useDeferredValue, useState } from 'react'
    
    function SearchPage({ products }) {
      const [search, setSearch] = useState('')
    
      const deferredSearch = useDeferredValue(search)
    
      const filteredProducts = products.filter((product) =>
        product.name
          .toLowerCase()
          .includes(deferredSearch.toLowerCase())
      )
    
      return (
        <>
          <input
            value={search}
            onChange={(event) => setSearch(event.target.value)}
            placeholder="Search products..."
          />
    
          <ProductList products={filteredProducts} />
        </>
      )
    }
    

    The input can update immediately while React defers the expensive list update.

    Unlike debouncing, useDeferredValue does not use a fixed time delay and does not reduce network requests by itself.

    It is a rendering-priority technique, not a replacement for API request throttling or debouncing.

    12. Use Transitions for Non-Urgent Updates

    Some updates are more important than others.

    For example, typing into a search field should feel immediate. Updating a large filtered table can be less urgent.

    React provides useTransition to mark certain state updates as non-urgent.

    import { useState, useTransition } from 'react'
    
    function SearchPage({ products }) {
      const [search, setSearch] = useState('')
      const [filteredSearch, setFilteredSearch] = useState('')
    
      const [isPending, startTransition] = useTransition()
    
      function handleSearch(event) {
        const value = event.target.value
    
        setSearch(value)
    
        startTransition(() => {
          setFilteredSearch(value)
        })
      }
    
      const filteredProducts = products.filter((product) =>
        product.name.toLowerCase().includes(
          filteredSearch.toLowerCase()
        )
      )
    
      return (
        <>
          <input
            value={search}
            onChange={handleSearch}
          />
    
          {isPending && <p>Updating results...</p>}
    
          <ProductList products={filteredProducts} />
        </>
      )
    }
    

    The urgent input update remains responsive while React can prioritize the transition update.

    A transition does not make expensive calculations inherently faster. It helps React schedule rendering work more intelligently.

    It also cannot be used to control the state of a text input directly.

    Reference: React — useTransition.

    13. Implement Code Splitting and Lazy Loading

    A large JavaScript bundle can delay the initial application load.

    Consider an application with these routes:

    /
     /dashboard
     /users
     /reports
     /settings
     /admin
    

    If every route and its dependencies are included in the initial bundle, users may need to download code for pages they never visit.

    Code splitting allows the application to load certain modules only when required.

    13.1 React.lazy

    React provides lazy() for loading components dynamically.

    import { lazy, Suspense } from 'react'
    
    const Dashboard = lazy(() => import('./pages/Dashboard'))
    const Reports = lazy(() => import('./pages/Reports'))
    const Settings = lazy(() => import('./pages/Settings'))
    
    function App() {
      return (
        <Suspense fallback={<p>Loading page...</p>}>
          <Dashboard />
        </Suspense>
      )
    }
    

    In a real routed application, the lazy components are rendered conditionally based on the current route.

    13.2 React Router Lazy Routes

    React Router supports route-level lazy loading.

    For example:

    import { createBrowserRouter } from 'react-router'
    
    const router = createBrowserRouter([
      {
        path: '/',
        lazy: () => import('./routes/home'),
      },
      {
        path: '/dashboard',
        lazy: () => import('./routes/dashboard'),
      },
      {
        path: '/reports',
        lazy: () => import('./routes/reports'),
      },
    ])
    

    The route modules can export their route properties, such as the component.

    export function Component() {
      return <h1>Dashboard</h1>
    }
    

    This separates route code into dynamically loaded modules.

    Check the documentation for your installed React Router version because routing APIs and package entry points can differ between major versions.

    13.3 Vite Dynamic Imports

    Vite supports dynamic imports and generates separate chunks during production builds.

    const loadEditor = () => import('./editor.js')
    

    The module is loaded when the dynamic import is executed.

    Vite also optimizes async chunk loading and can preload related dependencies.

    Official reference: Vite — Building for Production.

    14. Optimize Images and Static Assets

    Images can significantly affect page loading performance.

    A page containing large unoptimized images may feel slow even when its React code is efficient.

    Consider these techniques:

    Use Modern Image Formats

    Use formats such as:

    • WebP.
    • AVIF.

    These formats can reduce image file sizes compared with traditional formats, depending on image content and encoding settings.

    Provide Responsive Images

    Use srcSet and sizes to let the browser choose an appropriate image source.

    <img
      src="/images/product-800.webp"
      srcSet="
        /images/product-400.webp 400w,
        /images/product-800.webp 800w,
        /images/product-1200.webp 1200w
      "
      sizes="
        (max-width: 600px) 100vw,
        (max-width: 1000px) 50vw,
        33vw
      "
      alt="Product"
      width="800"
      height="600"
    />
    

    Lazy-Load Below-the-Fold Images

    <img
      src="/images/gallery.webp"
      alt="Gallery preview"
      loading="lazy"
      width="800"
      height="600"
    />
    

    Do not lazy-load an image that is critical to the initial viewport, especially the likely Largest Contentful Paint image.

    Reserve Image Dimensions

    Providing width and height helps the browser reserve layout space before the image loads.

    This reduces unexpected layout shifts.

    15. Optimize Network Requests and Data Fetching

    Frontend performance depends on more than rendering.

    Poor API request patterns can make a React application feel slow.

    15.1 Avoid Duplicate Requests

    A common issue is multiple components independently requesting the same data.

    Instead, use a shared data-fetching strategy.

    Libraries such as TanStack Query can provide:

    • Request caching.
    • Query deduplication.
    • Background refetching.
    • Retry handling.
    • Pagination.
    • Mutation management.

    Example:

    import { useQuery } from '@tanstack/react-query'
    
    function Users() {
      const {
        data,
        isLoading,
        isError,
      } = useQuery({
        queryKey: ['users'],
    
        queryFn: async () => {
          const response = await fetch('/api/users')
    
          if (!response.ok) {
            throw new Error('Unable to load users')
          }
    
          return response.json()
        },
      })
    
      if (isLoading) {
        return <p>Loading users...</p>
      }
    
      if (isError) {
        return <p>Failed to load users.</p>
      }
    
      return (
        <ul>
          {data.map((user) => (
            <li key={user.id}>{user.name}</li>
          ))}
        </ul>
      )
    }
    

    15.2 Use Pagination

    Do not fetch thousands of records when the user only needs to view a small portion.

    Use server-side pagination:

    GET /api/users?page=1&limit=20
    

    For large or frequently changing datasets, cursor-based pagination can provide better consistency and scalability than offset pagination.

    15.3 Avoid N+1 API Requests

    Suppose a product list contains 100 products and the application sends an additional request for each product's details.

    This can result in 101 requests.

    Instead, consider an API response that returns the required data in a single paginated request.

    The backend should also avoid introducing database-level N+1 queries while constructing that response.

    15.4 Cancel Obsolete Requests

    When users type quickly into a search field, previous requests may no longer be useful.

    Use AbortController:

    useEffect(() => {
      const controller = new AbortController()
    
      async function fetchUsers() {
        try {
          const response = await fetch(
            `/api/users?q=${encodeURIComponent(search)}`,
            {
              signal: controller.signal,
            }
          )
    
          if (!response.ok) {
            throw new Error('Request failed')
          }
    
          const data = await response.json()
    
          setUsers(data)
        } catch (error) {
          if (error.name !== 'AbortError') {
            console.error(error)
          }
        }
      }
    
      fetchUsers()
    
      return () => {
        controller.abort()
      }
    }, [search])
    

    This prevents obsolete requests from continuing unnecessarily and helps avoid outdated results replacing newer ones.

    16. Optimize CSS and Browser Rendering

    Not every performance problem comes from JavaScript.

    CSS and DOM complexity can also affect rendering.

    Consider these practices:

    • Avoid unnecessarily deep DOM structures.
    • Reduce expensive layout recalculations.
    • Avoid repeatedly reading and writing layout-sensitive DOM properties in loops.
    • Use CSS animations for suitable visual effects.
    • Prefer transform and opacity for animations where possible.
    • Reserve space for dynamically loaded content.
    • Avoid excessive blur and large-area shadows on performance-sensitive interfaces.

    For example:

    .card {
      transition:
        transform 180ms ease,
        opacity 180ms ease;
    }
    
    .card:hover {
      transform: translateY(-3px);
    }
    

    Avoid animating layout-heavy properties such as width, height, top, and left when a transform-based animation can achieve the same result.

    Always verify performance on the target devices rather than assuming a particular CSS technique will be faster in every situation.

    17. Understanding Core Web Vitals

    React rendering performance is only one part of the user experience.

    Google's Core Web Vitals measure important aspects of real-world website performance.

    The current Core Web Vitals are:

    MetricMeasuresGood target
    LCPLoading performance2.5 seconds or less
    INPInteraction responsiveness200 ms or less
    CLSVisual stability0.1 or less

    These targets are evaluated at the 75th percentile of page visits.

    17.1 Largest Contentful Paint (LCP)

    LCP measures when the largest visible content element is rendered.

    Common causes of poor LCP include:

    • Slow server responses.
    • Large unoptimized images.
    • Render-blocking resources.
    • Delayed loading of critical content.
    • Excessive JavaScript before the main content appears.

    Improvements include:

    • Optimizing the main image.
    • Improving server response time.
    • Reducing critical JavaScript.
    • Using appropriate image preloading when justified.
    • Avoiding lazy loading the LCP image.

    17.2 Interaction to Next Paint (INP)

    INP measures how responsive a page feels when users interact with it.

    Common problems include:

    • Long-running JavaScript.
    • Expensive event handlers.
    • Large synchronous computations.
    • Excessive component updates.
    • Blocking third-party scripts.

    Improvements include:

    • Breaking up long tasks.
    • Reducing unnecessary rendering.
    • Using transitions for non-urgent updates.
    • Moving suitable expensive computation to Web Workers.
    • Avoiding excessive work in event handlers.

    17.3 Cumulative Layout Shift (CLS)

    CLS measures unexpected visual movement during the page lifecycle.

    Common causes include:

    • Images without reserved dimensions.
    • Dynamically injected content.
    • Ads or embeds without reserved space.
    • Fonts that cause significant layout changes.
    • Components that appear above existing content.

    Improvements include:

    • Providing image dimensions.
    • Reserving space for dynamic content.
    • Using stable layout structures.
    • Managing font loading.
    • Avoiding unexpected insertion of elements above visible content.

    Reference: web.dev — Web Vitals.

    18. Measure Real-World Performance

    Lighthouse is useful for identifying performance problems in controlled tests.

    However, lab measurements cannot fully represent every user's device, network, and interaction patterns.

    Use both lab and field measurements.

    Useful tools include:

    ToolPurpose
    React Developer Tools ProfilerComponent rendering analysis
    Chrome PerformanceMain-thread and browser activity
    LighthouseLab-based performance audits
    PageSpeed InsightsLab and available field data
    Chrome UX ReportReal-user experience data
    Web Vitals libraryMeasuring Core Web Vitals in applications

    You can also collect Web Vitals programmatically.

    Install the library:

    npm install web-vitals
    

    Create src/performance/reportWebVitals.js:

    import {
      onCLS,
      onINP,
      onLCP,
    } from 'web-vitals'
    
    export function reportWebVitals() {
      onCLS(console.log)
      onINP(console.log)
      onLCP(console.log)
    }
    

    Call it once from your application entry point:

    import { reportWebVitals } from './performance/reportWebVitals'
    
    reportWebVitals()
    

    For production monitoring, send measurements to an analytics endpoint instead of relying on console output.

    Include useful context such as:

    • Metric name.
    • Metric value.
    • Page route.
    • Device category where available.
    • Navigation type.
    • Unique metric identifier.

    Respect user privacy and avoid collecting unnecessary personal information.

    19. React Performance Optimization Checklist

    Before releasing a React application, review the following areas.

    Component architecture

    • State is kept close to where it is needed.
    • Large components have meaningful boundaries.
    • Unnecessary Effects are removed.
    • Derived values are calculated rather than stored redundantly.
    • Context providers are split by responsibility where appropriate.

    Rendering

    • Expensive components have been profiled.
    • React.memo is used where it provides measurable value.
    • useMemo is reserved for useful calculations or stable references.
    • useCallback is used where stable function identity matters.
    • Unnecessary object and function recreation has been investigated.
    • Large lists are virtualized when necessary.

    Loading performance

    • Route-level code splitting is implemented.
    • Heavy components are loaded when needed.
    • Images are optimized.
    • Below-the-fold images are lazy-loaded.
    • Critical resources are not unnecessarily delayed.
    • JavaScript bundle size is reviewed.

    Data fetching

    • Duplicate requests are avoided.
    • Pagination is implemented for large datasets.
    • Obsolete requests can be cancelled.
    • API responses are appropriately cached.
    • Server-side filtering and sorting are used where appropriate.

    Measurement

    • React Profiler has been used.
    • Lighthouse has been reviewed.
    • Core Web Vitals are monitored.
    • Mobile performance is tested.
    • Improvements are measured against a baseline.

    Conclusion

    React performance optimization is not about using as many optimization hooks as possible.

    It is about understanding where time and resources are being spent and choosing the right solution.

    Start with component architecture and state placement. Measure expensive rendering work before introducing memoization. Use virtualization for large lists, code splitting for large applications, and appropriate data-fetching strategies for network-heavy interfaces.

    Most importantly, measure the complete user experience.

    A React application is not fast simply because its components render quickly. It must also load efficiently, respond immediately to interactions, and remain visually stable.

    By combining React profiling, sensible component design, optimized network requests, and Core Web Vitals monitoring, you can build applications that remain responsive as they grow.

    Official References

    1. React — Render and Commit
    2. React — memo
    3. React — useMemo
    4. React — useCallback
    5. React — useTransition
    6. React — You Might Not Need an Effect
    7. React Compiler
    8. Vite — Building for Production
    9. TanStack Virtual
    10. web.dev — Web Vitals
    11. web.dev — Core Web Vitals Thresholds
    12. Chrome DevTools Performance

    Enjoyed this read?

    Keep the conversation going.

    Follow along for more practical development notes, or reach out to talk about a project.

    Keep exploring

    Related articles

    More guides connected by the topics in this article.

    Browse the journal