How can I reduce unnecessary re-renders in React?

February 18, 2025

At PuppyAgent, we were developing a SaaS application with a React Flow workflow engine and RAG capabilities. One problem behind these notes was very concrete: workflow nodes kept re-rendering, and the editor felt slow. I started collecting explanations of Context, React.memo, Hooks, and keys to understand how those pieces related to the work React was doing.

When I drag a node, its position has to change on screen. The inspector for another node can often sit that update out. I start by tracing one interaction to the write that triggered it, then follow that write to the components that read the value.

What I observeWhat I would try first
An event handler saves a value for a later handler. Nothing on screen uses it.Keep it in a local ref.
An Effect sets state to a value already available from the current inputs.Derive the value during render.
Opening a small panel also renders the canvas.Move state down, or pass the canvas as children.
A command-only toolbar updates on every drag.Separate commands from changing data.
A parent renders again with the same inputs for an expensive child.Use a memo boundary and keep its props stable.
Editing one store record wakes unrelated rows.Narrow the selector and preserve unchanged references.

The examples use React 18. The state and Effects article follows an update through render and commit. The rename experiment measures Context and Redux. A second benchmark holds reader counts constant across React Redux, Zustand, and Jotai. I have no before-and-after timings for the original PuppyAgent slowdown.

Rendering is work, even when the DOM does not change

A source I saved at the time described the default parent-to-child behavior:

只要 parent component re-render,那我也要 re-render

Whenever the parent component re-renders, I also have to re-render. — My translation of Ray Lee (2023), “什麼情況下會觸發 re-render?”1

That is a useful starting point, with a qualification: React normally renders children as it processes their parent's output, but it can reuse work at appropriate boundaries. The statement is not an unconditional rule for every component, regardless of memoization or element identity.

Rendering means calling components to calculate their output. Committing means applying the necessary changes to the DOM. A component can run again and produce output that requires no DOM mutation.2 That still leaves the cost of executing its JavaScript and calculating that output.

For a workflow editor, distinguish three questions:

QuestionExample to investigate
What initiated an update?Node position, selection, or an open panel changed.
Which components became involved?A node card, every Context consumer, or an entire sidebar subtree rendered.
Where was time spent?React calculations, expensive node content, browser layout, or painting.

These are investigation categories, not established causes of our original slowdown. A repeated console message answers only a small part of them.

Nadia Makarevich's guide provides a useful companion to these notes, available in Chinese as 嘉欣Cansiny's 【译】React re-render 指南.34 One instruction in the translation addresses a common mistake:

在父组件内缓存 props 并不能阻止子组件的 re-render。

— 嘉欣Cansiny, “错误的做法:不必要的对 props 使用 useMemo/useCallback.”3

In other words, caching a prop value in the parent does not by itself stop the child from rendering. There must be a boundary that can reuse work, such as memo or reuse of the same JSX element. Unchanged props are useful to that boundary; they do not automatically create it.5

Custom Hooks also do not create component boundaries. The English guide puts it precisely:

Everything that is happening inside a hook “belongs” to the component that uses it.

— Nadia Makarevich, “Re-renders reason: hooks changes.”4

Moving a panel's state into usePanelState() still leaves that state in the component calling the Hook. For my workflow example, extracting the Hook alone would not isolate panel updates from the editor.

When can a ref save a render?

Suppose I want to record how long a node drag took. Only the drag handlers need the start time. Keeping it in state would ask React to render the owner when a new timestamp arrives. A ref keeps the timestamp across renders until the stop handler reads it.6

import { useRef } from 'react';
import { ReactFlow } from '@xyflow/react';

function TimedCanvas({ recordDuration, ...flowProps }) {
  const startedAt = useRef(null);

  function finishDrag() {
    const start = startedAt.current;
    if (start === null) return;
    startedAt.current = null;
    recordDuration(performance.now() - start);
  }

  return (
    <ReactFlow
      {...flowProps}
      onNodeDragStart={()=> { startedAt.current= performance.now(); }}
      onNodeDragStop={finishDrag}
    />
  );
}

The canvas owns the drag callbacks and the ref. Starting or clearing the timer schedules zero React updates of its own. Moving the node still updates its visible position, and updates from a parent or a subscription can still render the canvas. If the requirement changes to showing a live elapsed-time badge, the badge needs a reactive update for each displayed tick. A ref alone would leave the displayed time stale.6

Remove a second render caused by derived state

Suppose a node list shows a count of the selected nodes. If an Effect watches nodes and calls setSelectedCount, a selection change can commit once with the previous count and again with the new count. Calculate const selectedCount = nodes.filter(node => node.selected).length during the render that already has the updated nodes. The count then appears in that commit, with no second update to schedule. For an expensive calculation, useMemo can reuse the result while its inputs stay equal.78

Move state to the component that needs it

Before adding caches, I would check whether the state belongs in a smaller component. The guide describes moving state down and passing expensive content through children or another prop.34

For example, a help button and its panel can own their open/closed state together. Toggling that state then updates the small help component without initiating a render of the workflow editor above it. This is a different structural choice from the memoized label example later in this article.

I rewrote the guide's two composition diagrams below as illustrative JSX, using the workflow setting. These are new examples based on the source patterns, not historical application code or verbatim source excerpts.34 Each example uses useState from React and assumes an existing, non-memoized WorkflowCanvas component. Component definitions belong at module scope.

// Before: help state belongs to the whole editor.
function EditorBefore() {
  const [open, setOpen] = useState(false);
  return (
    <>
      <button onClick={()=> setOpen(value=> !value)}>Help</button>
      {open && <p>Drag a node to move it.</p>}
      <WorkflowCanvas /> {/* Renders again when help toggles. */}
    </>
  );
}

// After: only this small component owns the help state.
function HelpPanel() {
  const [open, setOpen]= useState(false);
  return (
    <>
      <button onClick={()=> setOpen(value=> !value)}>Help</button>
      {open && <p>Drag a node to move it.</p>}
    </>
  );
}

function EditorAfter() {
  return (
    <>
      <HelpPanel />
      <WorkflowCanvas /> {/* Help updates do not render EditorAfter. */}
    </>
  );
}

If state belongs to a wrapper around expensive content, the caller can instead supply that content as JSX: <ScrollFrame><WorkflowCanvas /></ScrollFrame>. When only ScrollFrame updates its local state, the caller does not recreate the child element. React can reuse that content. Named element props can serve the same purpose when there are several content regions.53

// Before: each changed scroll position renders the editor and canvas.
function ScrollingEditorBefore() {
  const [scrollTop, setScrollTop] = useState(0);
  return (
    <div
      style={{ height: 400, overflow: 'auto' }}
      onScroll={event=> setScrollTop(event.currentTarget.scrollTop)}
    >
      <output>Scroll: {scrollTop}px</output>
      <WorkflowCanvas />
    </div>
  );
}

// After: the wrapper updates while receiving the same child element.
function ScrollFrame({ children }) {
  const [scrollTop, setScrollTop] = useState(0);
  return (
    <div
      style={{ height: 400, overflow: 'auto' }}
      onScroll={event=> setScrollTop(event.currentTarget.scrollTop)}
    >
      <output>Scroll: {scrollTop}px</output>
      {children} {/* Local scroll updates do not recreate this JSX. */}
    </div>
  );
}

function ScrollingEditorAfter() {
  return <ScrollFrame><WorkflowCanvas /></ScrollFrame>;
}

The condition matters: the wrapper must receive the existing element from outside its own render. Creating <WorkflowCanvas /> inside the updating wrapper does not achieve the same separation. The canvas can still update because of its own state, Context subscriptions, or a render of the caller that creates it. Passing children is not a universal promise of skipped renders.

How does a nested node card get its data?

My draft suggested that Context could update a deeply nested child directly and avoid rendering its siblings. That conclusion was too broad.

蓝思绪 puts the reuse problem succinctly: “处于中间层的组件,有了一些它并不需要的属性”.9 Imagine a Canvas that accepts onRename solely to pass it to a NodeCard. A change to the card's editing API now touches a layout component too. If the caller already has the node, it can compose <Canvas><NodeCard node={node} onRename={rename} /></Canvas>. The card still has explicit props, and the canvas can arrange any children. For cards created deep in an editor, another option is to read the nearest provider with useContext(NodesContext).10

The rendering cost depends on who owns the state. Typing into a card's local draft schedules a render at the card. If the draft lives in Editor and the card calls its setter, the render starts at Editor, so React may call sibling components as it works down the tree. It only applies the necessary changes to the DOM.1

A provider at the root supplies one Context value to orange components on several branches. On the far right, a white component sits between two orange consumers.

Follow the rightmost branch. Both orange components read the provider's value. The white component between them can omit that value from its props. Illustration: “Using context in distant children,” from the React documentation, reproduced as lossless WebP under CC BY 4.0.

The subscription covers the whole provided value. React compares the previous value with the next one using Object.is. If they differ, a card that reads the Context receives the update, even if the particular field it uses stayed the same or the card is wrapped in memo.11

The draft's provider expression, value={tasks,setTasks}, also needs correction. To provide both values, use an object such as value={{ tasks, setTasks }}. However, that inline object is newly created each time the provider component renders.

A workflow equivalent can keep the wrapper object stable while its contents are unchanged:

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

export const NodesContext = createContext(null);

export function NodesProvider({ children }) {
  const [nodes, setNodes] = useState([]);
  const value = useMemo(() => ({ nodes, setNodes }), [nodes]);

  return (
    <NodesContext.Provider value={value}>
      {children}
    </NodesContext.Provider>
  );
}

The state setter has a stable identity.12 Memoizing the object avoids creating a new Context value merely because the provider rendered for another reason. It cannot keep that value stable when nodes actually changes. Consumers still receive those updates, including a consumer that reads only setNodes from the combined object.11

Separate data that changes for different reasons

Consider the same editor using useReducer. Dragging a node produces a new nodes array. The canvas needs those positions; the toolbar's “Add node” button only needs dispatch. If both read a single Context containing { nodes, dispatch }, both receive a Context update on the drag. React's task-list example puts state and dispatch in separate Contexts. Applied here, the canvas subscribes to the array and the toolbar subscribes to the stable dispatch function.13

After a node drag, a combined Context updates both Canvas and Toolbar. With separate Contexts, Canvas receives the new nodes and the dispatch value read by Toolbar stays stable.

Original diagram for this workflow example, following React's two-Context pattern. The arrows trace subscriptions for a single drag. A parent rendering the toolbar can still cause it to render through the ordinary component tree.1113

For a workflow editor, I would examine these possible boundaries:

DataTypical reason for changePotential consumers
Node positionsDraggingCanvas and connected edge geometry
Selected node IDSelectionSelection indicator and inspector
Node configurationEditing parametersThat node's content and its editor
Available commandsChanges in command dependenciesToolbar and menus

This is a way to question subscriptions, not a proposed replacement for React Flow's own state model. Keep a clear source of truth. If separate state is introduced for selection, for example, it must stay consistent with the selection events and programmatic changes the application supports.

Which editor does this toolbar control?

For a field I want to reuse in a workflow editor and a creation dialog, ordinary props give me the smallest interface. The parent supplies the current label and decides what an edit means.

function NodeNameField({ value, onChange }) {
  return (
    <label>
      Node name
      <input value={value} onChange={event=> onChange(event.target.value)} />
    </label>
  )
}

A dialog can pass its own draft and setter. A card connected to Redux can select the name by ID and supply a callback that dispatches a rename. Copying value into the field's own state would give it a second name to keep in sync when the user switches nodes or presses Undo. A separate draft earns its place when the UI offers Apply and Cancel.14

蓝思绪 raises a useful test for reuse: can the field render outside the editor? An adapter can read Context with useContext or Consumer, or read Redux with useSelector or connect, then pass ordinary props to the field. The adapter still needs a source. With no matching provider, React Context returns its declared default. A library can deliberately throw in its own Hook when that default is null. React Redux normally reports a missing store for a connected component.91516

For components designed to work together, nesting can express ownership directly:

<Editor>
  <Editor.Toolbar />
  <Editor.Canvas />
</Editor>

Imagine mounting that tree twice, for two workflows open side by side. If each Editor creates its own state and provides it through Context, each toolbar finds its own canvas and undo history through the nearest provider. The caller can see which history Undo will affect from the JSX alone. Typing into a draft held by one editor can stay local to that instance. This differs from the two Contexts in the drag diagram above, where two subscriptions share one reducer.10

If I wanted signals for fast-changing geometry, each editor could provide a stable model whose position signals are read by the canvas. Creating the model per editor keeps selection independent in the two panes. A module-level model would share it. Redux can offer the same public JSX interface, either by keying records by editor ID in a shared store or by creating a store per editor and binding its components to that store. I would take on that wiring when the editor needs the shared action history. The drag and reconnect example follows the cost of each subscription choice.16

Memoization depends on what crosses the boundary

Three APIs address different kinds of reuse:

APIWhat it can reuseWhat can invalidate the reuse
memo(Component)A component's rendered resultChanged props, its own state, or consumed Context
useMemo(calculate, dependencies)A calculation resultChanged dependencies
useCallback(callback, dependencies)A function referenceChanged dependencies

By default, memo compares each prop using Object.is, rather than deeply comparing object contents. It is a performance optimization, not a correctness mechanism.5 useMemo similarly caches a calculation; application correctness should not depend on that cache being retained.8

My Hooks draft preserved this concise definition:

useCallback is a React Hook that lets you cache a function definition between re-renders.

— React, useCallback, opening definition.17

It does not call the function or make the operation performed by that function faster. A function expression is still evaluated during rendering; React can return the cached reference when dependencies are unchanged.

Consider a node-label editor with a panel toggle unrelated to the labels:

import { memo, useCallback, useState } from 'react';

const initialNodes = [
  { id: 'retrieve', data: { label: 'Retrieve documents' } },
  { id: 'answer', data: { label: 'Generate answer' } },
];

const NodeLabel = memo(function NodeLabel({ id, label, onRename }) {
  return (
    <input
      aria-label={`Label for ${id}`}
      value={label}
      onChange={event=> onRename(id, event.target.value)}
    />
  );
});

export function WorkflowLabels() {
  const [nodes, setNodes] = useState(initialNodes);
  const [helpOpen, setHelpOpen] = useState(false);

  const renameNode = useCallback((id, label) => {
    setNodes(previous => {
      const target = previous.find(node => node.id === id);
      if (!target || target.data.label === label) return previous;

      return previous.map(node =>
        node.id === id
          ? { ...node, data: { ...node.data, label } }
          : node
      );
    });
  }, []);

  return (
    <section>
      <button onClick={()=> setHelpOpen(open=> !open)}>Toggle help</button>
      {helpOpen && <p>Edit a label to rename its node.</p>}
      {nodes.map(node => (
        <NodeLabel
          key={node.id}
          id={node.id}
          label={node.data.label}
          onRename={renameNode}
        />
      ))}
    </section>
  );
}

💡 Tip: Many languages support map, a standard functional programming operation that applies a function to each item. Here, nodes.map(...) turns each node into a <NodeLabel> element.18

Toggling help re-renders WorkflowLabels, but each NodeLabel receives the same ID, label, and callback reference. The memo boundary can therefore skip its work. Renaming one node changes that node's label prop while leaving the other label's props unchanged.

The callback uses a functional state update, so it does not close over nodes. Its empty dependency list is justified by the values it reads, not by a desire to suppress updates. If it later reads a changing prop, that dependency must be included.17

The inline onChange inside NodeLabel does not break this boundary: it is created inside the child when the child renders. Passing a fresh wrapper from the parent, such as onRename={(id, label) => renameNode(id, label)}, would instead change a prop on every parent render.

This example passes scalar props deliberately. When passing a data object or a complete node, preserving unchanged references also matters. Recreating every node object during a one-node edit can defeat shallow comparisons even when most contents are equal.

I would read the guide's advice to cache non-primitive props as advice about reference stability, rather than a requirement to wrap every object or function in a Hook.3 An unchanged object already held in state, a module-level constant, or a stable state setter may need no additional cache. Likewise, useMemo and useCallback are useful when their saved work or stable references serve a measured purpose; adding them everywhere makes the code harder to follow.125

What does one Redux dispatch cost?

Imagine an asset table in which exactly one laptop changes status. A Redux action gives the change a name. Middleware can observe it, and a reducer can replace the one record while preserving the other records' references. I like being able to follow that path when a transition goes wrong. There is ceremony in separating each role, but the separation often lets me change one step without disturbing the others.19

For rendering, ask three questions separately. Which selectors were evaluated? Which returned a value that compares unequal to the previous result? Which components actually rendered and committed work? React Redux's useSelector defaults to strict reference equality. Compare the following alternatives inside a subscribed row:19

// A primitive status can stay equal across unrelated dispatches.
const status = useSelector(state => state.assets.byId[id].status)

// This allocates a new object on each evaluation.
const badge = useSelector(state => ({ status: state.assets.byId[id].status }))

If A17 changes, the status for B22 can still compare equal. The second selector can schedule an update for B22 even when its status string stayed the same. Selecting a primitive, returning an existing object whose identity is preserved, or memoizing a genuinely derived result gives React Redux a useful equality check. Parent renders and Context changes can still bring the row into a render through a separate path. To investigate the table, count selector calls separately from commits recorded by the React Profiler.

What can a console trace tell us about Context and Redux?

蓝思绪 compares two versions of a greeting. Both display a username, load a user after a timer, and let a button rename that user. The Context version uses useState, and the Redux version uses a reducer and an external store. All the logged components run on mount. For the first rename after loading, the following is the expected trace from the code, assuming an ordinary update with no other work or development-only repeat calls.9

Component bodyContext exampleReact Redux example
The component logging “app render”App runs again because it owns the changed user state.The log is in InnerApp, which only calls useDispatch. Updating the external store gives it no new local state.
NavBarRuns again. It reads only setUser, but subscribes to the whole { user, setUser } value.Reads only dispatch and has no user subscription.
MainPage and ContentCan skip. The provider receives the same child elements from useMemo(..., []), and neither component reads the context.Neither subscribes, and their parent has no reason to render for this action.
MessageRuns again to display the changed name. React propagates the context update through the memoized children.Runs again. Its selector returns the whole user object, which the reducer replaced.

The load completion has the same subscription pattern. The interesting difference is the button: its only job is to issue a command, yet one version subscribes it to data and the other does not. The example also places the state owner in a logged component on only one side. Those are genuine differences between the two designs. A body log counts each invocation equally, however expensive it was. It cannot tell me how long the user waited for the greeting to change.111920

A controlled rename experiment

I adapted the greeting into five variants of the same production-mode example: four Context cases crossing useState or useReducer with combined or separate read/write contexts, and one Redux store whose message selects the whole user as in the original. All start with Bob. Clicking the same button alternates Bob and Tom, so every measured click changes the text. I removed the timer and thunk from this synchronous rename. The Context cases keep the same memoized child JSX throughout.21

Component calls per rename, after mountingCombined Context (either Hook)Split Contexts (either Hook)React Redux
Logged owner (App or Redux's InnerApp)110
Each command-only button100
Each layout wrapper (MainPage, Content)000
Each greeting displaying the new name111

With one button and one greeting, the instrumented components ran 3, 2 and 1 times respectively. Splitting the contexts kept the button's subscription on the stable command. Keeping the same child elements also prevented an ordinary parent render from recreating the button. Redux's dispatch-only readers had no user subscription, and the store update took place outside InnerApp. The remaining difference of one owner invocation says little about elapsed time. All three designs still had to change the greeting.

I then varied who actually needed the update. One stress case mounted 100 identical command-only buttons and clicked one. The other mounted 100 greetings, all displaying the changed name. Every timing below is the median microseconds per synchronous click and commit, with the middle half of the batch averages in parentheses.

Implementation1 button, 1 greeting100 buttons, 1 greeting1 button, 100 greetings
Combined Context, state11.9 (9.7–15.7)60.2 (54.7–68.7)69.7 (59.5–81.3)
Combined Context, reducer12.9 (10.7–15.7)60.7 (54.0–67.7)62.2 (58.0–82.8)
Split Contexts, state10.9 (9.2–15.4)14.9 (12.4–16.7)74.1 (61.4–79.4)
Split Contexts, reducer11.4 (9.2–14.2)14.9 (11.4–15.4)73.1 (56.2–76.6)
React Redux15.4 (11.7–16.9)16.4 (12.7–20.6)179.6 (171.4–193.3)

With 100 buttons, splitting the Context while keeping useState took button invocations from 100 to zero and reduced the median from 60.2 to 14.9 µs. With 100 greetings, every implementation ran all 100 readers. In that workload the Redux version took longer on this machine despite running fewer application component bodies. The timings include dispatch and subscription work, and the experiment does not isolate which internal step accounts for that gap.

The timing build compiled out the render counters. Each variant had its own root and fresh state per batch, 30 warm-up clicks, then 201 consecutive clicks. I rotated the order across 15 measured rounds after an initial warm-up cycle. Each click used flushSync to finish one DOM commit before the next. A separate counting build verified the greeting text on each counted click. These measurements cover JavaScript and synchronous DOM updates in headless Chrome. Browser paint, input latency on a real device and the cost of a React Flow drag are outside this measurement.21

Same 100 readers, different update costs

Dmitry Sky points out that changing a Context value updates every component reading it, while Jotai lets each component subscribe to an individual atom.22 Imagine a label that displays Sue while a button changes Bob to Tom. If both names travel in one Context value, Sue’s label renders again. With a separate atom for each name, changing Bob leaves Sue’s atom untouched. React Redux can also skip Sue’s label because the name its selector returns is still the same. If all 100 labels display Bob, though, every label needs the new text. How much does one click cost then?111923

I put 100 name labels on a page and changed A from Bob to Tom and back. B stayed Sue. In three runs, zero, one, or all 100 labels displayed A. The button had no data subscription. When one label displayed A, every implementation ran exactly one reader component per click. That still left a measurable difference in time.24

The first table measures a burst of updates immediately after mount in a React 18.3.1 production build. The script runs 30 warm-up clicks and 201 timed clicks in one JavaScript task, calling flushSync on each click. In the last column all 100 labels display the same changing name. Jotai 2.11.0’s primitive-atom hook took 1,064.2 µs per click (1.06 ms), about 9.4 times the 113.4 µs taken by the same Jotai store with React’s external-store hook. The follow-up experiment measures how much this comparison changes once React finishes its mount work.24

Production implementation0 of 100 change (µs/click)1 of 100 changes (µs/click)All 100 change (µs/click)
Redux + React Redux11.9 (9.5–13.2)19.9 (19.4–28.4)170.1 (158.2–177.9)
Zustand, one store12.4 (9.0–13.9)20.4 (17.7–25.6)103.5 (88.3–110.7)
Jotai, separate primitive atoms7.5 (6.7–11.2)28.4 (25.4–34.8)1,064.2 (1,051.2–1,081.3)
Jotai, one object and two derived atoms10.9 (8.2–14.9)35.3 (29.4–36.6)1,136.3 (1,127.1–1,184.6)
Control: Jotai primitive atoms + React external-store hook10.4 (7.0–11.4)19.4 (16.7–24.1)113.4 (98.8–121.9)

The numbers are microseconds per click through the synchronous React update, including the text changes to the DOM. Each cell shows the median and interquartile range of 15 batch averages, with 201 clicks per batch after 30 warm-ups. The harness rotated the implementations and workloads, ran the counters in a separate build, and checked the resulting text. All readers stayed mounted. These are in-page scripting and commit timings on one machine; browser paint, hydration and network latency are separate costs.24

Where can a library skip work? In the earlier Context test, changing the combined Provider value reached the button even though the button only issued commands. React 18.3.1 compares the old and new Provider values and schedules consumers whose recorded dependency matches that Context. When I split the two Contexts, the command-only button read a stable value. The parent also reused its child elements. Together those two conditions explain why all 100 button calls disappeared.25

The three store libraries have different paths from a write to a reader:

  • React Redux 8.1.3. Redux runs the reducer and notifies the store listeners. React Redux's Provider forwards that notification to its nested subscriptions. Each useSelector reader checks its selected snapshot. A and B are strings here. In the one-label case the 100 subscriptions evaluated their selectors 100 times per click, 99 results stayed equal, and one reader ran. The reducer was plain Redux 4.2.1, with no Redux Toolkit middleware or Immer.26
  • Zustand 4.5.5. The vanilla store replaces the state object and invokes its listeners. Its React binding passes the store's own subscribe and getState to useSyncExternalStoreWithSelector. Here too the counter recorded 100 selector calls and one reader call. React Redux and Zustand both finish by comparing selected values. The additional notification layer in React Redux is visible in source; timing the whole click cannot tell us how much of the difference that layer accounts for.27
  • Jotai 2.11.0. With separate primitive atoms for A and B, writing A reaches A's mounted listeners. The 99 readers of B have no dependency on A. With one object atom and two shared derived atoms, updating the object caused two derived field reads per click in the one-label case, one for A and one for B. The unchanged B value produced no reader call. Jotai records dependencies when a derived atom reads another atom and uses Object.is to detect a value change. Fewer application-level field reads still left work inside the store and React binding.23

Why did Jotai take so long when all 100 labels changed?

The first clue was the last row. I kept the same primitive atom, store, write and 100 labels, and replaced useAtomValue with useSyncExternalStore wired to the atom's subscription and snapshot. The median dropped from 1,064.2 to 113.4 µs. Both implementations still had to update all 100 labels. This control handles synchronous values only. To find out what the public hook was doing, I counted calls to store.get(atom) during each click.24

In Jotai 2.11.0, the first render reads the atom. An Effect then subscribes and requests one more check. That catches a write that could have happened between the initial read and the subscription. Here is the synchronous path, simplified for a fixed store and atom. Each call to the reducer reads the current name, even if the equality check ultimately reuses the previous value.23

const [name, checkName] = useReducer(previous => {
  const next = store.get(nameAtom)
  return Object.is(previous, next) ? previous : next
}, undefined, () => store.get(nameAtom))

useEffect(() => {
  const unsubscribe = store.sub(nameAtom, checkName) // check on each write
  checkName()                                       // also check once on mount
  return unsubscribe
}, [store, nameAtom])

React 18.3.1 gives that Effect's update default priority. Each simulated click in the test uses flushSync, which makes its update urgent. On the first click, React skips the pending mount check and processes the click. To preserve update order, React keeps the skipped entry and a copy of the click entry in the hook's queue. On the second click the mount check is still waiting, so React runs the reducer for the first click and the second click. Both calls read the current atom. Each label can therefore execute its component body once and read the atom twice inside that one render. As long as the loop keeps issuing synchronous clicks without yielding, those entries accumulate.28

I repeated the all-100 workload with one change. In half the batches I let React finish its scheduled mount work before starting the same click loop. The wait was outside the timer. The timings below are medians from this second run, with 15 batches per cell. A separately instrumented build counted the reads on the first ten clicks.29

All 100 labels show the edited nameClick immediately (µs/click)Let mount work finish (µs/click)
Redux + React Redux102.0103.0
Zustand61.267.7
Jotai, primitive atom737.872.6
Jotai, derived atom744.884.6
Same primitive atom + React external-store hook67.768.7

The read counts pin down what changed. With the stock primitive-atom hook, immediate clicks produced 100, 200, 300, …, 1,000 reads across the labels. After mount work finished, every click produced 100 reads. For a second control I kept the immediate clicks and omitted only the one-off checkName() in a diagnostic build. That also produced 100 reads on every click. The subscription callback stayed active, and all 100 labels showed the correct name after each click. Removing the check in an application would leave the render-to-subscription gap uncovered.2923

With the same primitive-atom hook in both runs, immediate clicks took 10.2 times as long as clicks after mount work finished (737.8 versus 72.6 µs per click). The immediate loop repeatedly ran queued reducer updates. Even 30 warm-up clicks prolonged the queue because they ran in the same task. Both columns still use a tight loop. To see what happens when a person has time to release the button and click again, I changed how the browser received the input.29

What happens when clicks arrive one at a time?

I kept the same button and the same 100 labels, all displaying the edited name. This time Playwright moved the mouse to the button, pressed it for 40 ms and released it. Before the next press the driver waited 160, 260 or 360 ms. Each click reached the page as a separate browser input event, and React chose when to commit it. The script used flushSync only to mount the initial page.30

The timer started when the button received the browser's click event and stopped when a MutationObserver first saw the changed text. The test then checked the new name in all 100 labels. This measures the page's response through the DOM update. The pause, button hold, time spent waiting for input dispatch and subsequent screen paint are outside that interval. Each implementation had five fresh mounts in rotating order, with two warm-up clicks and twelve measured clicks per mount.30

All 100 labels change, 60 individual clicks per rowMedian (ms/click)95th percentile (ms/click)
Redux + React Redux0.801.2
Zustand0.600.9
Jotai, primitive atom0.601.0
Jotai, derived atom0.650.9
Same primitive atom + React external-store hook0.600.9

The measured clicks arrived 203–408 ms apart. In a separate counting build, each of five spaced clicks on the primitive atom produced exactly 100 atom reads and 100 reader calls. Each label read its name once per click, including on the fifth. Under this pacing, Zustand and the stock Jotai primitive hook both had a median of 0.60 ms. The synchronous burst in the first table explains how a queue can grow. For a user clicking this button on an already mounted page, the spaced measurements give a closer estimate of the work through the DOM change. The two tables use different timing boundaries. With just 60 observations per implementation and timestamps in roughly 0.1 ms steps, small differences in this table carry little weight.30

Why did the Redux row take longer on spaced clicks?

The first run measured a 0.20 ms gap between React Redux and Zustand. Each click changed the string displayed by all 100 readers. The Redux reducer ran once per dispatch, so there was one state update to follow through the binding and 100 components that needed the new name. This test used Redux 4.2.1 directly, without middleware or Immer.2630

Both bindings use useSyncExternalStoreWithSelector, the hook that connects a store to React and selects the value for a component. Two of the arguments differ. Here is the client-side comparison in abbreviated form.2627

// React Redux 8.1.3
useSyncExternalStoreWithSelector(
  subscription.addNestedSub, store.getState, getServerSnapshot, wrappedSelector, equalityFn
)

// Zustand 4.5.5
useSyncExternalStoreWithSelector(
  api.subscribe, api.getState, getServerSnapshot, selector, equalityFn
)

Who tells the readers? React Redux's Provider subscribes to the Redux store and forwards the notification to its list of reader callbacks. Zustand registers the readers with its store directly. The React Redux path adds one forwarding step per dispatch in this tree. Both paths still visit 100 reader callbacks.2627

What runs inside a reader? React Redux builds a named wrapper around the application's selector and passes it through useCallback. That hook can reuse the previous function when its dependencies match. The production wrapper calls the application's selector and returns its result. The extra selector calls used for development checks are compiled out. Zustand passes the supplied selector through directly. With 100 readers displaying a single string, the binding code runs alongside a very small amount of application logic.2627

I repeated the spaced clicks with four builds of the same Redux example. One edit subscribed the readers directly to the store. The other passed the original stable selector in place of the entire useCallback wrapper. The reducer, action, Provider, equality check and rendered labels stayed the same across the four builds. Zustand ran alongside them as a reference. Each row covers 60 timed clicks, measured from click capture to the DOM observer.31

Reader implementationMedian (ms/click)95th percentile (ms/click)
React Redux 8.1.3 as shipped0.901.6
React Redux, only subscribe directly0.801.4
React Redux, only pass the original selector0.701.5
React Redux, both edits0.701.6
Zustand 4.5.5 as shipped0.701.2

In the separate counting build, every variant made 100 application selector calls and 100 reader calls on each of five clicks. Passing the original selector while keeping the Provider's notification path brought the median down to the Zustand median in this run. Changing only the notification path moved it by one timer step. That points to the work around the selector as a plausible contributor when 100 very small readers update together. The selector edit removes both wrapper preparation during render and the extra call through the wrapper, so the data cannot assign a cost to either one individually. The two edits' median differences also do not add up, and the 95th percentiles still differ. The stopwatch covers the complete click through the DOM change.31

For the workflow editor, I would first check which readers really depend on a drag. An unchanged neighboring node and 100 labels that all display the changing name are different workloads. The first gives a narrow subscription something to skip. In the second, every label has to update, and render counts alone conceal most of the difference between implementations.

Can the editor state load with its route?

Suppose the user opens a workflow list and might never open the editor. If only the lazy editor route imports its draft provider, the editor's UI and state logic can load together on demand. A shared Redux store can do this too. A static import of editorReducer in the root reducer puts it on the initial load path. Loading the slice with the editor and calling editorSlice.injectInto(rootReducer) there lets a Redux Toolkit store built with combineSlices defer that code. The feature must arrange injection before readers rely on its state. Creating several stores and importing them all at startup would still load their code eagerly.32

I would decide draft lifetime separately. A draft held in the route component's useState disappears when that component unmounts. If the provider was passing an externally owned model, unmounting the provider leaves other references to that model intact. A Redux store follows the same JavaScript reachability rules. For an app-wide store, the memory question is how many closed workflows its cache or undo history still retains.15 If returning from the list should restore unsaved work, a longer-lived owner such as the application store can keep it by workflow ID. For bundle size I would inspect which modules the list route actually downloads. I used the same distinction when comparing Preact and Solid for a SQL query manager.

Apply the same reasoning to React Flow

React Flow's performance guidance calls out frequent node updates, custom component memoization, stable function and object props, and overly broad node subscriptions.33 These are useful places to investigate a slow workflow canvas:

  1. Declare custom node components at module scope. Creating a component type inside a rendering parent can reset identity; this is different from merely passing a new callback.
  2. Keep an unchanging nodeTypes mapping outside the parent, and memoize custom node content where measurements justify it. Stable type identity and skipped renders are separate concerns.
  3. Keep callbacks and configuration props stable when they cross a boundary that benefits from stable references.
  4. Inspect subscriptions. A panel needing only selection information should not automatically subscribe to every node-position update.

These measures do not freeze a dragged node. Its changed position must still reach the canvas. They aim to limit unrelated work around that necessary update. Even an efficient React component tree can remain slow if a large diagram has expensive styles or browser painting costs; measure those separately.

Keys preserve identity; they do not memoize a component

My original notes mixed a second issue into render avoidance: list keys. The legacy documentation explains their purpose:

Keys help React identify which items have changed, are added, or are removed.

— React, Lists and Keys, “Keys.”34

If a workflow list changes from [retrieve, answer] to [load, retrieve, answer], stable node IDs let React match the two existing items across the insertion. With index keys, the old first position can be reused for load, even though its local state previously belonged to retrieve. The reconciliation notes discuss both matching children and the state problems caused by reordering index-keyed items.35

Use the domain ID, as in key={node.id} above. It needs to be unique among siblings and stable for the lifetime of that item. Do not generate a fresh random key during rendering. React's fallback to positions does not invent a durable domain identity for the data.34

A stable key can preserve a component and its local state while that component renders again. Conversely, deliberately changing a key can reset state. For example, an inspector's unsaved local form state might be intentionally reset when switching to a different selected node, provided discarding that draft matches the product's requirements.36

The list tutorial and index-key article in my notes illustrate the same practical issue.3738 Their relevance here is identity and correctness. A unique key is not evidence that an expensive component will skip rendering.

Use DevTools to connect an interaction to the work it causes

The Developer Tools draft contained only a link. Its useful place in this article is the investigation loop. React DevTools provides component inspection and profiling tools for understanding props, state, and performance.39

For a workflow-node slowdown, I would use this procedure:

  1. Choose one repeatable interaction. Drag one node, edit one parameter, or toggle one panel. Keep the diagram and environment consistent between comparisons.
  2. Record a short Profiler trace. Identify which subtrees contribute meaningful render time, rather than treating every component invocation as equally costly.
  3. Inspect the relevant inputs. Look for changed node data, fresh callback references, a changed Context value, or subscriptions broader than the UI needs.
  4. Change one boundary and repeat the interaction. Check both responsiveness and correctness: selection, form state, and subscriptions must still behave as intended.
  5. Inspect browser work if React does not explain the delay. Use the browser performance timeline to investigate layout, painting, or other long-running JavaScript.

Development profiling helps locate causes, but Strict Mode adds intentional checks and development builds have overhead. Evaluate actual responsiveness with a production build as well; collecting React render timings there requires a profiling-enabled build.40 Do not equate duplicate development logs with duplicate DOM changes or a production performance regression.

For a reusable editor, I would start with Context because the JSX already tells me which instance owns a toolbar. I find the implementation easier to follow when the context names say what each component needs. A toolbar that only issues commands can read a stable command context. An inspector that displays the selection can read a separate selection context. Putting both in one object called EditorContext would still group them by feature, but it would also subscribe the toolbar to selection changes.1113

In the rename experiment, that read/write split let Context and React Redux skip all 100 command-only buttons. The Context state owner still ran once. With 100 greetings that actually needed the new name, both designs rendered every greeting, and their measured times differed. For this editor, the reason I prefer Context is that ownership is visible at the call site and the commands have a natural boundary. If each canvas row needs a different field from a frequently changing collection, a Redux selector can express that dependency directly in the row.1921

References

Footnotes

  1. Lee, R. [Ray Lee | 李宗叡]. (2023, July 26). React Render [Blog post]. Learn or Die, Medium. “什麼情況下會觸發 re-render?” https://medium.com/learn-or-die/react-re-render-5caf1bd3e316 ↩ ↩2

  2. React. (n.d.). Render and commit. https://react.dev/learn/render-and-commit ↩

  3. 嘉欣Cansiny. (2022, August 29). 【译】React re-render 指南 [Translated blog post]. 稀土掘金. Translation of Nadia Makarevich's guide. Sections “Re-renders 原因:hooks 改变,” “通过组合防止 re-render,” “错误的做法:不必要的对 props 使用 useMemo/useCallback,” and “必要的 useMemo/useCallback.” https://juejin.cn/post/7137309684045709348. Text, byline, date, and image links verified against a user-supplied HTML copy on November 17, 2026. ↩ ↩2 ↩3 ↩4 ↩5 ↩6

  4. Makarevich, N. (2022, August 2). React re-renders guide: everything, all at once [Blog post]. Developer Way. “Re-renders reason: hooks changes,” opening paragraph, and “Preventing re-renders with composition.” https://www.developerway.com/posts/react-re-renders-guide. Current page checked November 17, 2026; the displayed publication date does not establish that its contents have remained unchanged since 2022. ↩ ↩2 ↩3 ↩4

  5. React. (n.d.). memo. “Parameters” and “Usage.” https://react.dev/reference/react/memo ↩ ↩2 ↩3 ↩4

  6. React. (n.d.). useRef. React documentation. Referencing a value with a ref. Rubets, S. (2022, May 22). React useRef, forwardRef and some problems you may run into working with them. HackerNoon, interval examples comparing ref and state writes. ↩ ↩2

  7. React. (n.d.). You might not need an Effect. React documentation. Updating state based on props or state. ↩

  8. React. (n.d.). useMemo. “Caveats.” https://react.dev/reference/react/useMemo ↩ ↩2

  9. 蓝思绪. (n.d.). React-Redux 与 Context 之个人浅见. 稀土掘金. “问题总结,” third bullet, “可重用性,” and “使用对比 / 程序性能”. ↩ ↩2 ↩3

  10. React. (n.d.). Passing data deeply with context. React documentation. Context passes through intermediate components. ↩ ↩2

  11. React. (n.d.). useContext. “Caveats” and “Optimizing re-renders when passing objects and functions.” https://react.dev/reference/react/useContext ↩ ↩2 ↩3 ↩4 ↩5 ↩6

  12. React. (n.d.). useState. “set functions,” Caveats. https://react.dev/reference/react/useState#setstate ↩ ↩2

  13. React. (n.d.). Scaling up with reducer and context. React documentation. Step 1: Create the context. ↩ ↩2 ↩3

  14. React. (n.d.). Sharing state between components and Choosing the state structure. React documentation. Controlled components, mirroring props in state. ↩

  15. React. (n.d.). createContext and Preserving and resetting state. React documentation. Default value and context object, component state lifetime. ↩ ↩2

  16. React Redux maintainers. (n.d.). Accessing the store. React Redux documentation. Providing custom context. Preact contributors. (n.d.). Signals for React. GitHub. React integration. ↩ ↩2

  17. React. (n.d.). useCallback. Opening definition, “Skipping re-rendering of components,” and “Updating state from a memoized callback.” https://react.dev/reference/react/useCallback ↩ ↩2

  18. MDN contributors. (2026, October 26). Array.prototype.map(). MDN Web Docs. Syntax. ↩

  19. React Redux maintainers. (n.d.). Hooks. React Redux documentation. Selector results and equality comparisons. Redux maintainers. (n.d.). Performance. Normalization and selecting by ID. ↩ ↩2 ↩3 ↩4 ↩5

  20. React. (n.d.). Profiler and StrictMode. React documentation. Render duration for a committed update, development render checks. ↩

  21. Cai, B. (2026, November 19). Context and Redux rename experiment [Local reproduction]. React and React DOM 18.3.1, React Redux 8.1.3, Redux 4.2.1, Chrome 138.0.7204.92, Linux on an AMD Ryzen 7 8845HS. Components, runner, counts and batch timings. To reproduce with Node 22 and Chrome installed, run npm ci and then node run.mjs in the experiment directory. ↩ ↩2 ↩3

  22. Sky, D. (2024, January 23). React Context vs Redux vs Jotai. Medium. Overview of the three models, “Summary”. ↩

  23. Jotai contributors. (n.d.). Store and React binding (v2.11.0). GitHub. Store implementation: addDependency, recomputeDependents, subscribeAtom, useAtomValue subscription, reducer and async handling. ↩ ↩2 ↩3 ↩4

  24. Cai, B. (2026, November 23). 100 subscribed readers [Local benchmark]. React and React DOM 18.3.1, headless Chrome 138.0.7204.92, Linux, AMD Ryzen 7 8845HS. Reader implementations and control, runner, per-batch timings and two-click counts. In the experiment directory run npm ci and node run.mjs --readers with Node 22 and Chrome installed. Each batch starts with a fresh root and store. Both the Node and ESM production flags are set when bundling. ↩ ↩2 ↩3 ↩4

  25. React contributors. (2024). React reconciler (v18.3.1). GitHub. Compare the Provider values, match Context dependencies and schedule work. ↩

  26. Redux maintainers. (n.d.). createStore (v4.2.1). GitHub. Reducer and listener loop. React Redux maintainers. (2023). React bindings (v8.1.3). GitHub. Provider notification, listener traversal, selector wrapper, memoization and subscription. ↩ ↩2 ↩3 ↩4 ↩5

  27. Zustand contributors. (2024). Vanilla store and React binding (v4.5.5). GitHub. State replacement and listener notification, React subscription and selection. ↩ ↩2 ↩3 ↩4

  28. React contributors. (2024). React reconciler (v18.3.1). GitHub. Effect update priority in flushPassiveEffects, skipping, retaining and replaying reducer updates. ↩

  29. Cai, B. (2026, November 23). Immediate and settled mount comparison [Local benchmark]. Same environment as the reader test. Run node run.mjs --startup after npm ci. The settled variant waits for an idle-priority callback on React's scheduler before the 30 warm-ups. Counts cover ten clicks without warm-ups. Only the diagnostic counting bundle omits the mount check for the extra control. Runner and single-line control, per-click counts and all 150 timing samples. ↩ ↩2 ↩3

  30. Cai, B. (2026, November 23). Spaced browser clicks on 100 name labels [Local benchmark]. Same environment as the reader test. Run node run.mjs --pointer after npm ci. Input driver, DOM observer and text checks, individual timings, event spacing and read counts. Playwright contributors. (n.d.). Mouse.click. Mouse input and hold duration. WHATWG. (n.d.). DOM Standard. Mutation observers. ↩ ↩2 ↩3 ↩4

  31. Cai, B. (2026, November 23). React Redux subscription and selector controls with spaced clicks [Local benchmark]. Run node run.mjs --redux-pointer in the same environment as the pointer test. Each variant uses its own foregrounded timing page and a separate counting build. The modified builds change only the indicated parts of the installed React Redux 8.1.3 hook during bundling. Source edits and runner, per-click timings and counts. ↩ ↩2

  32. Redux maintainers. (n.d.). Code splitting. Redux documentation. Reducer injection and selectors for lazy slices. ↩

  33. xyflow. (n.d.). Performance. React Flow documentation. https://reactflow.dev/learn/advanced-use/performance ↩

  34. React. (n.d.). Lists and keys. Legacy documentation, “Keys.” https://legacy.reactjs.org/docs/lists-and-keys.html#keys ↩ ↩2

  35. React. (n.d.). Reconciliation. Legacy documentation, “Recursing On Children” and “Keys.” https://legacy.reactjs.org/docs/reconciliation.html#keys ↩

  36. React. (n.d.). Preserving and resetting state. “Resetting state with a key.” https://react.dev/learn/preserving-and-resetting-state#option-2-resetting-state-with-a-key ↩

  37. Emma, M. B. (2023, April 10). How to render lists in React using array.map(). freeCodeCamp. https://www.freecodecamp.org/news/how-to-render-lists-in-react/ ↩

  38. Pokorny, R. (2015, October 11). Index as a key is an anti-pattern [Blog post]. https://robinpokorny.com/blog/index-as-a-key-is-an-anti-pattern/ ↩

  39. React. (n.d.). React Developer Tools. https://react.dev/learn/react-developer-tools ↩

  40. React. (n.d.). Profiler. “Caveats.” https://react.dev/reference/react/Profiler#caveats ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-02-18). How can I reduce unnecessary re-renders in React?. https://caiborui.com/blog/2025-02-18-en-how-can-i-reduce-unnecessary-re-renders-in-react

@misc{borui2025-d2e128a8,
  author = {borui},
  title = {{How can I reduce unnecessary re-renders in React?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-02-18-en-how-can-i-reduce-unnecessary-re-renders-in-react}
}