React Performance

By Lucas Bittencourt · · Updated

Table of contents:

How React renders

In React, a single component can have nested components. When a component renders, all its children are rendered together by default.

A render happens when:

  • The component's state changes
  • Its parent component renders
  • A context it uses changes

The update process can be broken down into 2 parts:

  1. Render: React calls your components and builds a new tree of elements (the "virtual DOM"), then compares it with the previous tree using a diffing algorithm called reconciliation
  2. Commit: React applies only the differences to the real DOM

Without reconciliation, updating the real DOM on every render would be extremely slow. But keep in mind: even when nothing changes in the DOM, the render itself (calling your components) still has a cost. Most performance optimizations in React are about skipping unnecessary renders or making them cheaper.

Read more about render and commit here

Memoization

It's a technique that saves the return value of pure functions, avoiding heavy recalculations. Pure functions are functions that don't depend on external values; therefore, they always return the same result given the same input.

React components are expected to be pure as well: given the same props and state, they should return the same JSX.

Referential equality

When we say referential equality, it means that we need to ensure reference types are equal when they have not changed.

In JavaScript we have primitive types and reference types.

  • Two identical primitive types are always equal in a shallow comparison (e.g. 25 === 25, 'Lucas' === 'Lucas', true === true).
  • Two identical reference types are not equal in a shallow comparison (e.g. { age: 25 } === { age: 25 }, ['Lucas'] === ['Lucas']). Therefore, if you create them during the render, they are different on every render.

React compares values with Object.is (similar to ===), so we need these reference types (objects, arrays and functions) to keep the same reference between renders in these scenarios:

  • The dependencies array of useEffect, useMemo and useCallback
  • Props of memoized components

React Compiler

React Compiler (stable since v1.0, in 2025) is a build-time tool that automatically memoizes your components and hooks. It analyzes your code and applies the equivalent of useMemo, useCallback and memo where it's needed, with more precision than doing it by hand.

With Next.js, enable it in next.config.ts after installing babel-plugin-react-compiler:

import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  reactCompiler: true,
};

export default nextConfig;

With the compiler enabled, you can write plain code and let it handle memoization:

function TodoList({ todos, filter }: TodoListProps) {
  // memoized automatically, no useMemo needed
  const visibleTodos = filterTodos(todos, filter);

  // stable reference automatically, no useCallback needed
  const handleClick = (id: string) => toggleTodo(id);

  return <List items={visibleTodos} onClick={handleClick} />;
}

The compiler only works with code that follows the Rules of React (pure components, no mutation of props or state during render). The ESLint plugin eslint-plugin-react-hooks reports code that breaks these rules.

Even with the compiler, it's important to understand useMemo, useCallback and memo: you will find them in existing codebases, and they still work as escape hatches.

React Hook: useMemo

Syntax:

const memoizedValue = useMemo(() => expensiveFunction(), dependencies);

You use useMemo to memoize values, helping avoid heavy recalculations or to maintain referential equality.

1. Avoiding heavy recalculations

Don't do this:

// this runs on every render
const filteredList = heavyFunction(myList);

Do this instead:

// this runs only when myList changes
const filteredList = useMemo(() => heavyFunction(myList), [myList]);

2. Maintaining referential equality

Don't do this:

const person = { name: props.name, age: props.age };

// this runs on every render, because person is a new object every time
useEffect(() => {
  console.log(person);
}, [person]);

Do this instead:

const person = useMemo(
  () => ({ name: props.name, age: props.age }),
  [props.name, props.age]
);

// this runs only when person changes
useEffect(() => {
  console.log(person);
}, [person]);

React Hook: useCallback

Syntax:

const memoizedFunction = useCallback(functionToMemoize, dependencies);

You use useCallback to memoize functions, allowing you to maintain referential equality.

Don't do this:

const doSideEffect = () => setTimeout(console.log, 1000);

// this runs on every render, because doSideEffect is a new function every time
useEffect(() => {
  const timeout = doSideEffect();

  return () => clearTimeout(timeout);
}, [doSideEffect]);

Do this instead:

const doSideEffect = useCallback(() => setTimeout(console.log, 1000), []);

// this runs only once
useEffect(() => {
  const timeout = doSideEffect();

  return () => clearTimeout(timeout);
}, [doSideEffect]);

With dependencies:

const doSideEffect = useCallback(
  () => setTimeout(() => console.log(name), 1000),
  [name]
);

// this runs only when name changes
useEffect(() => {
  const timeout = doSideEffect();

  return () => clearTimeout(timeout);
}, [doSideEffect]);

React: memo

Syntax:

const MemoizedComponent = memo(Component, arePropsEqual?);

As we know, when a component renders, all its children are rendered by default. To skip rendering a component whose props have not changed, we can memoize it with the memo function. By default, it compares every prop with Object.is (a shallow comparison).

function UserCard({ user, onSelect }: UserCardProps) {
  return <button onClick={() => onSelect(user.id)}>{user.name}</button>;
}

const MemoizedUserCard = memo(UserCard);

memo only works if the props keep the same reference. If the parent passes a new object or function on every render (e.g. onSelect={(id) => select(id)}), MemoizedUserCard renders anyway. That's why memo is usually combined with useMemo and useCallback (or the React Compiler).

You can pass a custom comparison function. It must return true when the props are equal (to skip the render):

function arePropsEqual(prevProps: UserCardProps, nextProps: UserCardProps) {
  return prevProps.user.id === nextProps.user.id;
}

const MemoizedUserCard = memo(UserCard, arePropsEqual);

Why should we use the key property in loops?

Syntax:

{
  list.map((item) => <p key={item.id}>{item.text}</p>);
}

The key attribute helps React identify which items have changed, are added, or are removed between renders. With stable keys, React can move existing elements instead of recreating them. The key should be a unique and stable identifier, such as an ID from your data.

Why should not we use the index in loops?

Syntax:

{
  list.map((item, index) => <p key={index}>{item.text}</p>);
}

When an item is added, removed or reordered, the indexes change, so React matches the wrong elements:

  • Performance: React updates the content of many elements instead of just moving them.
  • Bugs: the state of a component (e.g. an input value or a checkbox) stays with the index, not with the item, so it appears in the wrong item after a reorder or removal.

Using the index is only fine when the list is static (never reordered, filtered or changed). Also avoid key={Math.random()}: it creates a new key on every render, so React recreates every element every time.

Resetting a component with key

You can also use key outside of loops. When the key changes, React destroys the component and creates a new one, resetting all its state.

// the form state resets when another user is selected
<ProfileForm key={user.id} user={user} />

Avoiding derived states

Derived states are states created from another state or props. They need effects to stay in sync, which causes extra renders and bugs.

Don't do it!

const [repos, setRepos] = useState<Repo[]>([]);
const [search, setSearch] = useState("");
const [filteredRepos, setFilteredRepos] = useState<Repo[]>([]);

// renders twice: once with the old filteredRepos, then again after the effect
useEffect(() => {
  setFilteredRepos(repos.filter((repo) => repo.name.includes(search)));
}, [search, repos]);

Do it!

const [repos, setRepos] = useState<Repo[]>([]);
const [search, setSearch] = useState("");

// calculated during the render
const filteredRepos = repos.filter((repo) => repo.name.includes(search));

We don't need an additional state derived from another state. We can just create a new variable during the render (and use useMemo if the calculation is heavy and you don't use the React Compiler).

You Might Not Need an Effect

Keeping the UI responsive: useTransition and useDeferredValue

Sometimes a render is heavy and can't be skipped (e.g. filtering and rendering a big list on every keystroke). With concurrent rendering, React can mark some updates as non-urgent and interrupt them to handle urgent ones, such as typing.

useDeferredValue lets you defer the part of the UI that depends on a value:

function SearchPage({ items }: SearchPageProps) {
  const [query, setQuery] = useState("");

  // the input updates immediately, the list updates when React has time
  const deferredQuery = useDeferredValue(query);
  const isStale = query !== deferredQuery;

  return (
    <>
      <input value={query} onChange={(event) => setQuery(event.target.value)} />

      <div style={{ opacity: isStale ? 0.5 : 1 }}>
        <SlowList items={items} query={deferredQuery} />
      </div>
    </>
  );
}

SlowList must be memoized (with memo or the React Compiler), otherwise it renders with the parent anyway.

useTransition marks a state update as non-urgent, and gives you an isPending flag:

function Tabs() {
  const [tab, setTab] = useState("home");
  const [isPending, startTransition] = useTransition();

  function selectTab(nextTab: string) {
    startTransition(() => {
      setTab(nextTab);
    });
  }

  return (
    <>
      <TabButtons onSelect={selectTab} isPending={isPending} />
      {tab === "home" && <Home />}
      {tab === "reports" && <SlowReports />}
    </>
  );
}

Prefer these hooks over manual debounce when the slow part is rendering. Debounce is still useful to reduce network requests.

Code splitting with lazy and Suspense

The less JavaScript the browser downloads, parses and executes, the faster the page loads. With lazy, a component is loaded only when it's rendered for the first time.

import { lazy, Suspense } from "react";

// loaded only when the chart is shown
const Chart = lazy(() => import("./chart"));

function Dashboard({ showChart }: DashboardProps) {
  return (
    showChart && (
      <Suspense fallback={<p>Loading chart...</p>}>
        <Chart />
      </Suspense>
    )
  );
}

Next.js already splits your code by route, and provides next/dynamic for the same purpose.

Rendering long lists

Rendering thousands of DOM elements is slow, no matter how well you memoize them. Use virtualization: render only the items visible on the screen, with libraries such as TanStack Virtual.

For simpler cases, the CSS property content-visibility: auto lets the browser skip the rendering work of off-screen elements.

Server Components

With Server Components (e.g. the Next.js App Router), components run only on the server, and their JavaScript is never sent to the browser.

  • Fetch data directly on the server, close to the database, without client-side waterfalls.
  • Keep heavy libraries (e.g. markdown parsers, syntax highlighters, date libraries) on the server.
  • Use "use client" only in the components that need interactivity (state, effects, event handlers), and keep them as small and as deep in the tree as possible.

Code snippet:

// Server Component: no JavaScript shipped for this component
export default async function PostPage({ params }: PostPageProps) {
  const { slug } = await params;
  const post = await getPost(slug);

  return (
    <article>
      <h1>{post.title}</h1>
      <PostContent content={post.content} />

      {/* only this small component is sent to the browser */}
      <LikeButton postId={post.id} />
    </article>
  );
}

Measure before optimizing

Don't guess, measure. Most components are fast enough, and unnecessary optimizations make the code harder to read.

  • Use the Profiler tab of React Developer Tools to see which components render, why, and how long they take.
  • Use the Performance panel of the browser DevTools to find long tasks.
  • Track Core Web Vitals (LCP, INP, CLS) of real users, e.g. with Vercel Speed Insights.