💡 This is the legacy site for v11. If you are looking for the latest docs, please visit React Flow
Reference
useOnSelectionChange()

useOnSelectionChange

Source on GitHub (opens in a new tab)

This hook lets you listen for changes to both node and edge selection. As the name implies, the callback you provide will be called whenever the selection of either nodes or edges changes.

You need to memoize the passed onChange handler, otherwise the hook will not work correctly.

import { useState, useCallback } from 'react';
import ReactFlow, { useOnSelectionChange } from 'reactflow';
 
function SelectionDisplay() {
  const [selectedNodes, setSelectedNodes] = useState([]);
  const [selectedEdges, setSelectedEdges] = useState([]);
 
  // the passed handler has to be memoized, otherwise the hook will not work correctly
  const onChange = useCallback(({ nodes, edges }) => {
    setSelectedNodes(nodes.map((node) => node.id));
    setSelectedEdges(edges.map((edge) => edge.id));
  }, [])
 
  useOnSelectionChange({
    onChange
  });
 
  return (
    <div>
      <p>Selected nodes: {selectedNodes.join(', ')}</p>
      <p>Selected edges: {selectedEdges.join(', ')}</p>
    </div>
  );
}

Signature

#Params
#options
object
#options.onChange
(params: { nodes: Node[]; edges: Edge[]; }) => void
#Returns
void

Notes