The Best Way to Optimize React Flow Project Performance
Learn the best way to optimize React Flow performance: memoize nodes, stabilize props, narrow store selectors, and render only visible elements.
Quick answer: how do you optimize React Flow performance?
The best way to optimize React Flow performance is to eliminate unnecessary re-renders. Dragging a node updates state dozens of times per second, so memoize custom nodes and edges, keep every prop passed to <ReactFlow> referentially stable, subscribe to small slices of state instead of the whole nodes array, keep heavy UI out of nodes, and enable viewport rendering for large graphs. Verify each change with the React Profiler.
React Flow is an open-source React library (published as @xyflow/react) for building node-based editors, diagrams, and workflow builders. It is easy to start with and just as easy to slow down, because one careless line can re-render every node on every mouse move.
Why does React Flow slow down?
React Flow is state-driven. When you drag a node, it emits position changes, your handler applies them to the nodes array, and the store notifies every subscriber. Each tick of the drag produces a new nodes array.
To hold 60 FPS you have roughly 16.7 milliseconds per frame for scripting, layout, and paint combined. Re-rendering one component fits easily inside that budget. Re-rendering a hundred nodes, each holding a form field or a data table, on every tick does not.
The trigger can be tiny. In a performance audit published by Visual flow, a single inline arrow function passed to onNodeClick dropped a 100-node diagram from 60 FPS to about 10 FPS while dragging, and to about 2 FPS when each node contained a data grid. That result matches the official React Flow documentation: most React Flow performance problems are re-render problems rather than drawing problems.
Step 0: Measure before you optimize
Guessing wastes time. Set up a repeatable measurement first.
- Use a production build. Development mode and StrictMode double rendering exaggerate costs. Close DevTools while reading FPS.
- Record a drag in the React DevTools Profiler. Start recording, drag one node for a few seconds, stop, and open the flamegraph. A healthy result commits only the dragged node and its connected edges. An unhealthy one shows many nodes in the same commit.
- Turn on update highlighting. React DevTools can flash components as they render, and tools such as react-scan do the same, which makes runaway renders obvious.
- Bisect by elimination. Return an empty
divfrom your custom node. If dragging becomes smooth, the cost lives in node content. Repeat by removing sidebars, panels, and<ReactFlow>props one half at a time. - Keep a fixed fixture. Use the same graph (for example, 200 nodes) every time so you can prove each fix helped.
Fix 1: Memoize custom nodes and edges, and define types outside
Wrap every custom node and edge in React.memo, and declare nodeTypes and edgeTypes at module scope so their identity never changes.
codeimport { memo } from 'react'; import { Handle, Position, type Node, type NodeProps } from '@xyflow/react'; type TaskNodeType = Node<{ label: string }, 'task'>; const TaskNode = memo(function TaskNode({ data, selected }: NodeProps<TaskNodeType>) { return ( <div className={selected ? 'task task--selected' : 'task'}> <Handle type='target' position={Position.Top} /> <span>{data.label}</span> <Handle type='source' position={Position.Bottom} /> </div> ); }); // Module scope: the reference never changes between renders const nodeTypes = { task: TaskNode };
If nodeTypes is created inside a component without useMemo, a new object appears on every render, React Flow warns about it in the console, and node performance suffers.
Memoization only works if unchanged nodes keep their identity. When you update one node, return the same object for every other node:
codesetNodes((nodes) => nodes.map((n) => (n.id === id ? { ...n, data: { ...n.data, label } } : n)) );
Fix 2: Keep every <ReactFlow> prop referentially stable
Functions passed to <ReactFlow> belong in useCallback. Objects and arrays such as defaultEdgeOptions, snapGrid, and fitViewOptions belong in module-level constants or useMemo.
code// Slow: a new function and new objects are created on every render <ReactFlow nodes={nodes} edges={edges} nodeTypes={nodeTypes} onNodeClick={() => openInspector()} defaultEdgeOptions={{ type: 'smoothstep' }} snapGrid={[16, 16]} /> // Fast: stable references const defaultEdgeOptions = { type: 'smoothstep' }; const snapGrid: [number, number] = [16, 16]; function Diagram() { const onNodeClick = useCallback( (_: React.MouseEvent, node: Node) => openInspector(node.id), [openInspector] ); return ( <ReactFlow nodes={nodes} edges={edges} nodeTypes={nodeTypes} onNodeClick={onNodeClick} defaultEdgeOptions={defaultEdgeOptions} snapGrid={snapGrid} /> ); }
Memoized callbacks are only as stable as their dependencies. If a dependency is a value derived from the whole nodes array, the callback changes on every drag tick and useCallback achieves nothing. Read current data on demand inside the handler instead, with useReactFlow().getNodes() or your store’s getState().
Fix 3: Stop subscribing to the whole nodes array
Hooks such as useNodes() and useEdges(), and selectors that return state.nodes or a filtered copy of it, re-evaluate on every position change. A .filter() always returns a new array, so reference equality fails even when the contents are identical.
codeimport { useStore } from '@xyflow/react'; import { shallow } from 'zustand/shallow'; // Re-renders on every drag tick: new array reference each time const selected = useStore((s) => s.nodes.filter((n) => n.selected)); // Re-renders only when the set of selected IDs actually changes const selectedIds = useStore( (s) => s.nodes.filter((n) => n.selected).map((n) => n.id), shallow );
The selector still runs on each store update, but running a cheap function is far less expensive than re-rendering a component tree. Prefer these patterns:
- Return primitives (IDs, booleans, counts) from selectors wherever you can.
- Read on demand in event handlers with
useReactFlow()instead of subscribing. - Use
useNodesData(id)when a component needs one node’s data. - Track selection separately. Copy selection into its own store field through
onSelectionChange(memoized) oruseOnSelectionChange, so components never derive it from the nodes array.
Fix 4: Manage state with a selector-friendly store
React Flow uses Zustand internally, and its docs point to it for state management. Keeping nodes and edges in useState or Context pushes the entire diagram state through the tree, while a Zustand store lets each component subscribe to just the slice it needs.
codeimport { create } from 'zustand'; import { applyNodeChanges, applyEdgeChanges, addEdge, type Node, type Edge, type OnNodesChange, type OnEdgesChange, type OnConnect, } from '@xyflow/react'; type FlowState = { nodes: Node[]; edges: Edge[]; onNodesChange: OnNodesChange; onEdgesChange: OnEdgesChange; onConnect: OnConnect; }; export const useFlowStore = create<FlowState>((set, get) => ({ nodes: [], edges: [], onNodesChange: (changes) => set({ nodes: applyNodeChanges(changes, get().nodes) }), onEdgesChange: (changes) => set({ edges: applyEdgeChanges(changes, get().edges) }), onConnect: (connection) => set({ edges: addEdge(connection, get().edges) }), }));
codeimport { useShallow } from 'zustand/react/shallow'; const { nodes, edges, onNodesChange, onEdgesChange, onConnect } = useFlowStore( useShallow((s) => ({ nodes: s.nodes, edges: s.edges, onNodesChange: s.onNodesChange, onEdgesChange: s.onEdgesChange, onConnect: s.onConnect, })) );
A common pitfall: in current Zustand versions, a selector that returns a new array or object literal on every call can cause an infinite render loop and the error “Maximum update depth exceeded.” Wrap multi-field selectors in useShallow, or create the store with createWithEqualityFn from zustand/traditional and shallow so every selector compares shallowly by default.
Fix 5: Keep heavy UI out of the drag path
Memoize expensive node content
Even a memoized node re-renders when its own data or selected state changes. Wrap the expensive piece inside it (a data grid, chart, or rich editor) in its own memo so it re-renders only when its props change.
Show summaries in nodes, details elsewhere
Render a lightweight summary in the node (title, status icon, two or three fields) and open the full form or table in a side panel for the selected node. You mount one form instead of a hundred, and every node carries far less DOM.
Memoize panels and children of <ReactFlow>
Components rendered as children of <ReactFlow> can re-render along with it, so wrap your own in React.memo. Sidebars outside the flow should subscribe through narrow selectors, never to the nodes array.
Keep typing local
For text inputs inside nodes, hold the value in local state while the user types and commit to the store on blur or after a debounce. Add the nodrag class to inputs so typing and clicking do not start a drag, and nowheel to scrollable areas so scrolling does not zoom the canvas.
Move expensive work out of drag handlers
onNodeDrag fires continuously. Validation, autosave, and layout belong in onNodeDragStop, or behind a debounce.
Fix 6: Scale to large graphs
Render only what is visible
<ReactFlow onlyRenderVisibleElements />
This prop is off by default. When enabled, React Flow mounts only nodes and edges inside the viewport. The trade-off: nodes mount and unmount as users pan, so keep node state in your store rather than in local component state, and keep mounting cheap.
Snap to grid
With snapToGrid, a node’s position changes only when it crosses a grid step, so the store updates far less often during a drag.
<ReactFlow snapToGrid snapGrid={snapGrid} />
Collapse large trees
For hierarchical graphs, set hidden: true on the nodes and edges of collapsed branches and reveal them on expand. The official docs recommend this approach for large node trees, because hidden elements are not rendered.
Switch to simpler nodes when zoomed out
A boolean selector re-renders a node only when zoom crosses your threshold, not on every pan or zoom tick.
codefunction TaskNodeBase({ data }: NodeProps<TaskNodeType>) { const zoomedOut = useStore((s) => s.transform[2] < 0.5); return ( <div className='task'> <Handle type='target' position={Position.Top} /> {zoomedOut ? <strong>{data.label}</strong> : <TaskDetails data={data} />} <Handle type='source' position={Position.Bottom} /> </div> ); } export const TaskNode = memo(TaskNodeBase);
Keep the handles in both modes so edges stay attached.
Simplify CSS and animation
If you have fixed re-renders and large graphs still stutter, look at paint cost. Box shadows, gradients, filters, and animation across hundreds of elements are expensive, which the React Flow docs also call out. Use flat styles, animate only selected or hovered edges, and never put a CSS transition on a node’s transform, because it makes dragging lag behind the pointer.
Keep layout work off the hot path
Run auto-layout (Dagre, ELK) only when the graph structure changes, never during a drag. For large graphs, consider running ELK in a Web Worker.
Fix 7: Structure your app so regressions are easy to find
Separate container components (they read the store and hold logic) from presentational components (props in, markup out, memoized). Performance bugs almost always hide in containers, so when the Profiler shows unexpected renders, start there.
Two habits keep the gains. Enable the react-hooks/exhaustive-deps lint rule so unstable dependencies get flagged, and treat useNodes() and useEdges() as code-review red flags.
Troubleshooting: symptom, cause, fix
Symptom
Likely cause
Fix
Many nodes highlight in the Profiler while dragging one
Unstable <ReactFlow> prop, or nodes not memoized
Fix 1 and Fix 2
Sidebar or form lags during drag
It subscribes to the nodes array
Fix 3
“Maximum update depth exceeded” after adding a selector
Selector returns a new array or object each call
useShallow or createWithEqualityFn
Smooth with 20 nodes, janky with hundreds
Too many mounted nodes or heavy node content
Fix 5 and Fix 6
Dragging is fine but pan and zoom stutter
Paint cost from shadows, gradients, or many edges
Simplify CSS, onlyRenderVisibleElements
Console warning about new nodeTypes
nodeTypes created inside a component
Module scope or useMemo
React Flow performance checklist
- Profile a production build and record a baseline FPS.
- Declare
nodeTypesandedgeTypesat module scope (or withuseMemo). - Wrap every custom node and edge in
React.memo. - Wrap function props in
useCallbackand object or array props in constants oruseMemo. - Check that no dependency array contains values derived from the whole nodes array.
- Replace broad subscriptions with narrow selectors that return IDs, booleans, or counts, compared with shallow equality.
- Keep nodes and edges in Zustand instead of Context.
- Memoize heavy node content and move large forms and tables into a side panel.
- Move expensive work from
onNodeDragtoonNodeDragStop, or debounce it. - For large graphs, enable
onlyRenderVisibleElements, snap to grid, collapse subtrees, and add zoom-based detail. - Remove shadows, gradients, and animation from nodes and edges that do not need them.
- Re-profile and confirm that dragging one node re-renders only that node and its edges.
Frequently asked questions
Why is my React Flow diagram slow when I drag nodes?
Dragging triggers frequent state updates. If custom nodes are not memoized, <ReactFlow> props change identity on every render, or components subscribe to the full nodes array, many nodes re-render on each update. Profile with React DevTools, then fix unstable props, memoize nodes, and narrow your selectors.
How many nodes can React Flow handle?
There is no fixed limit. It depends on node complexity, the user’s device, and how well the app is optimized. Lightweight, memoized nodes combined with onlyRenderVisibleElements stay responsive at far larger sizes than nodes containing data grids or charts. Test with a fixture that resembles your real data.
Should I wrap every custom node in React.memo?
Yes. The React Flow documentation recommends memoizing custom node and edge components, or declaring them outside the parent component. Memoization is cheap and stops a node from re-rendering when only other nodes change. Also memoize any expensive content inside the node.
Does onlyRenderVisibleElements always improve performance?
Not always. It reduces the number of mounted nodes on large graphs, but nodes mount and unmount as users pan, and local component state is lost. It helps most when many nodes sit off-screen and each is costly to render. Benchmark before enabling it on small graphs.
Should I use useState, Context, or Zustand for nodes and edges?
For anything beyond a small diagram, use Zustand. React Flow uses it internally, and selectors let each component subscribe to only the data it needs. Context re-renders every consumer whenever its value changes, which is costly when node positions update constantly.
How do I find which components re-render during a drag?
Record a drag in the React DevTools Profiler and inspect the flamegraph, or enable update highlighting. In a well-optimized app, only the dragged node and its connected edges re-render. If many nodes appear in one commit, look for unstable props and broad store subscriptions.
Conclusion
React Flow performance is rarely about the canvas and almost always about React re-renders. Measure first, then work top-down: memoize nodes and edges, stabilize props, narrow subscriptions, move heavy UI out of nodes, and apply large-graph options such as onlyRenderVisibleElements only when the numbers call for them. Re-profile after every change, and treat a single dragged node re-rendering alone as your definition of done.
Related Engineering Articles

Visualizing Complex Pipelines with Flow Weaver and React Flow
Learn how to build a highly interactive, customizable visual builder and workflow orchestration tool using the premium Flow Weaver template.

Building UML Sequence Diagrams with React Flow
Learn the complex architectural layout algorithms required to build structured, rigid UML sequence diagrams and timelines using React Flow.

Architecting for Massive Scale in React Flow
A comprehensive guide on handling thousands of nodes with virtualized rendering and advanced minimap optimization in React Flow.