Skip to content

Commit 965ca70

Browse files
committed
fix(react): don't call useCallback conditionally in MiniMap
onSvgNodeClick was built with a useCallback inside a ternary, so the hook only ran when onNodeClick was provided. Two problems followed: - toggling onNodeClick between undefined and a function changes the hook count and React throws "Rendered more hooks than during the previous render" - the empty dependency array pinned the callback to the onNodeClick from the first render, so handlers that close over props or state kept using stale values Call the hook unconditionally and read the handler through a ref, so the callback identity stays stable for the memoized minimap nodes while always invoking the current onNodeClick. onSvgNodeClick is still undefined when no handler is passed.
1 parent 6eee160 commit 965ca70

2 files changed

Lines changed: 18 additions & 6 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@xyflow/react": patch
3+
---
4+
5+
Fix `MiniMap` calling `useCallback` conditionally for `onNodeClick`, which crashed with "Rendered more hooks than during the previous render" when the prop was toggled on or off, and pinned the handler to its first-render value.

‎packages/react/src/additional-components/MiniMap/MiniMap.tsx‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -141,12 +141,19 @@ function MiniMapComponent<NodeType extends Node = Node>({
141141
}
142142
: undefined;
143143

144-
const onSvgNodeClick = onNodeClick
145-
? useCallback((event: MouseEvent, nodeId: string) => {
146-
const node: NodeType = store.getState().nodeLookup.get(nodeId)!.internals.userNode;
147-
onNodeClick(event, node);
148-
}, [])
149-
: undefined;
144+
/*
145+
* the handler is kept in a ref so that the callback identity stays stable for
146+
* the memoized minimap nodes while still calling the current onNodeClick
147+
*/
148+
const onNodeClickRef = useRef(onNodeClick);
149+
onNodeClickRef.current = onNodeClick;
150+
151+
const nodeClickHandler = useCallback((event: MouseEvent, nodeId: string) => {
152+
const node: NodeType = store.getState().nodeLookup.get(nodeId)!.internals.userNode;
153+
onNodeClickRef.current?.(event, node);
154+
}, []);
155+
156+
const onSvgNodeClick = onNodeClick ? nodeClickHandler : undefined;
150157

151158
const _ariaLabel = ariaLabel ?? ariaLabelConfig['minimap.ariaLabel'];
152159

0 commit comments

Comments
 (0)