When switching React Flow workspaces, why does getNodes() still return an empty array after setNodes()?

March 7, 2025

I ran into a reproducible problem while implementing workspace switching in PuppyFlow. I would create an edge in the previous workspace, then switch back to one with unsaved changes. The node array passed to setNodes() contained data, yet the canvas was blank. The console showed no error, and calling getNodes() after waiting still returned [].1 2

In the early hours of March 8 I selected the three lines I was trying in Cursor. Only the variable names are simplified below. flow is the instance returned by useReactFlow(), and saved is the graph to restore.1

flow.deleteElements({ nodes: flow.getNodes(), edges: flow.getEdges() })
flow.setNodes(saved.nodes)
flow.setEdges(saved.edges)

Reading those lines, it is easy to imagine two successive frames: the old graph clears, then the new one appears. I wanted to know why deletion still seemed to happen after setNodes().

When is deleteElements() finished?

The March 2025 documentation contained a discrepancy that directly affected how to write those lines. The ReactFlowInstance overview listed the return type of deleteElements as void. The dedicated DeleteElements page in the same documentation showed a Promise that delivers deletedNodes and deletedEdges. The type definitions in the project’s pinned @xyflow/react 12.3.2 matched the dedicated page.3 4

An await in the source determines the ordering. When deleteElements() is called, React Flow retrieves the current graph’s nodes and edges, then waits for getElementsToRemove() to determine which elements to delete. That step also considers any onBeforeDelete supplied by the application. Once the result is back, it invokes deletion callbacks for matching elements, emits the changes, and finally returns the deletion result. If the caller carries straight on, it may already have called setNodes() by the time the deletion changes are emitted.4

If the application needs to process deletion before requesting restoration, it can await flow.deleteElements(...). When the Promise resolves, the method has emitted the corresponding changes. The visual update still has to wait for React to commit the state update to the UI.

What does getNodes() read when setNodes() returns?

On the evening of March 7 I selected setNodes([]) in Cursor and asked why this failed to clear the canvas. In the same conversation I asked how to install a particular older version and confirm which version was actually installed. That evening I opened line 131 of an older useReactFlow.ts on GitHub. It happened to be the start of setNodes, and the first thing it did was queue the supplied value. Looking through the file history, upstream had moved the individual queues maintained by each useReactFlow() call into a shared BatchProvider. The project’s pinned 12.3.2 already contained that fix and still queued updates.5

In 12.3.2, flow.setNodes(saved.nodes) queues the array and returns. flow.getNodes() reads the nodes React Flow currently holds internally. If the old graph is empty, nothing between those lines guarantees that the new array has been applied. Adding await to setNodes() cannot wait for this either. The method returns void and supplies no update result to await.6

PuppyFlow uses a controlled canvas: the application holds nodes and edges and passes them to <ReactFlow>. When the queue processes a node update, it compares the target array against existing nodes and sends the resulting changes to the application’s onNodesChange. The historical documentation contains an easily missed line: “Calling this function will trigger the onNodesChange handler in a controlled flow.” Even with the right array passed to the instance, check which changes the application received and which nodes it actually passed back on the next render.7 Edges have a corresponding queue. When restoring links with setEdges(saved.edges), inspect the edge changes received by onEdgesChange.68

What does waiting another five seconds rule out?

I tried waiting for deletion to complete and also removed an extra setViewport(). Switching still failed. Sometimes the canvas was blank. Sometimes it still showed the previous workspace. In one attempt I set a five-second timer before calling setNodes() and setEdges(), then a second five-second timer before reading the result. It still came back empty. Reading too early on the next line could no longer explain that reproduction on its own.1

Why does comparing two getNodes() results fail to wait for an update?

The code I committed on March 11 kept two distinct paths. With a cached unsaved graph, it directly restored it using setNodes(unsavedState.nodes) and setEdges(unsavedState.edges). It only called deleteElements() and emptied both arrays if the target workspace had no history or no workspace was selected. The earlier delete-then-restore sequence was something I actually tried in the editor. The commit also added code intended to detect when switching had finished.9

Before switching I saved the node array in currentNodes and the edge array in currentEdges. If the old graph had nodes or edges, the code checked currentNodes === reactFlowInstance.getNodes() || currentEdges === reactFlowInstance.getEdges() and waited in a loop while that expression was true. The revealing detail is in the getters. In 12.3.2 both getNodes() and getEdges() use .map() to produce new arrays on every call. Even if no node has moved, successive results are different array objects. Both reference comparisons return false and the loop never runs. The type signature alone only says you get an array. The implementation explains why the “wait for loading” log cannot measure loading progress.6 9

How can I tell at which step the target graph disappears?

If I investigated again, I would keep the same reproduction — create an edge in the previous workspace and switch back — and trace the same transition in three places.

  1. When reading the cache, record the target workspace ID and the node and edge IDs about to be restored. This distinguishes an empty cache from reading a different graph.
  2. At the change callbacks, record the change types and element IDs received by onNodesChange and onEdgesChange. This shows whether deletion changes for those same elements arrived after the restore request.
  3. After the controlled canvas commits, log the actual IDs from a useEffect that depends on nodes and edges in the component that owns them. If the target nodes appear and then disappear, look for the state writer between those commits. If they never appear, follow the restore request and callbacks backward.

The source explains why calling deletion first can still emit deletion changes later. It also explains why a read immediately after setNodes() cannot confirm successful restoration. The surviving logs are insufficient to locate the exact step where the graph was lost in that switch. Looking back, tracking a single node ID to its last appearance would tell me more than waiting another few hundred milliseconds.

Footnotes

  1. CaiBorui. (2025, March 7–8). Setting Default Viewport in React Flow and ReactFlow State Management and Race Condition [Unpublished development conversations]. Cursor. In the first conversation, user messages 3 and 5 concern clearing nodes and checking the installed version. In the second, message 1 contains the three selected lines, message 5 the nested timers and reproduction feedback, message 7 the code after awaiting deletion, and messages 11 and 15 the previous workspace remaining visible after a switch. ↩ ↩2 ↩3

  2. CaiBorui. (2025, March 7–11). PuppyFlow workspace switching and unsaved graph restoration [Project code and debugging notes]. GitHub. Nodes, edges, and change handlers bound to the controlled canvas · Branch logic to cache, restore, or clear the canvas on a switch · March 11 commit adding switch logs. Dated March 7, when I began examining the source. The commit from that date identifies the code version. ↩

  3. xyflow. (2025, March 5). ReactFlowInstance and DeleteElements [Documentation source snapshot e815891]. GitHub. Overview return type, lines 37–41 · Return type on the method page. Both are from the same revision retained in a public fork. ↩

  4. xyflow. (n.d.). ReactFlowInstance types and useReactFlow [@xyflow/react 12.3.2]. GitHub. Deletion method type definition · Awaiting the removal list, emitting changes, and returning results. ↩ ↩2

  5. xyflow. (2024, April 25). fix(react): handle setNodes batching in provider #4147 [Git commit]. GitHub. Earlier implementation, lines 131–139 · Change moving batched updates to the shared provider. ↩

  6. xyflow. (n.d.). useReactFlow and BatchProvider [@xyflow/react 12.3.2]. GitHub. Queuing nodes and edges · Reading current nodes · Queue processing and controlled callbacks. ↩ ↩2 ↩3

  7. xyflow. (2025, March 5). ReactFlowInstance fields [Documentation source snapshot e815891, last sentence of the setNodes entry]. GitHub. setNodes parameters and controlled canvas behavior. ↩

  8. xyflow. (n.d.). ReactFlowInstance (setEdges) and OnEdgesChange (callback arguments). React Flow. Checked December 2, 2026. ↩

  9. CaiBorui. (2025, March 11). add more log output for flow switching [Git commit 20c4c62c]. GitHub. Restoring from the unsaved cache · Clear branch, timers, and array comparison. ↩ ↩2

© 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-03-07). When switching React Flow workspaces, why does getNodes() still return an empty array after setNodes()?. https://caiborui.com/blog/2025-03-07-zh-react-flow-delete-elements-set-nodes-entrans

@misc{borui2025-76c15c7d,
  author = {borui},
  title = {{When switching React Flow workspaces, why does getNodes() still return an empty array after setNodes()?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-03-07-zh-react-flow-delete-elements-set-nodes-entrans}
}