useNodesState()

Source on GitHub

This hook makes it easy to prototype a controlled flow where you manage the state of nodes and edges outside the ReactFlowInstance. You can think of it like React’s useState hook with an additional helper callback.

import { ReactFlow, useNodesState, useEdgesState } from '@xyflow/react';
 
const initialNodes = [];
const initialEdges = [];
 
export default function () {
  const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
  const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
 
  return (
    <ReactFlow
      nodes={nodes}
      edges={edges}
      onNodesChange={onNodesChange}
      onEdgesChange={onEdgesChange}
    />
  );
}

Signature

This hook makes it easy to prototype a controlled flow where you manage the state of nodes and edges outside the ReactFlowInstance. You can think of it like React’s useState hook with an additional helper callback.

Parameters
  • initialNodes: NodeType[]
Returns

[nodes: NodeType[], setNodes: Dispatch<SetStateAction<NodeType[]>>, onNodesChange: OnNodesChange<NodeType>]

TypeScript

This hook accepts a generic type argument of custom node types. See this section in our TypeScript guide for more information.

const nodes = useNodesState<CustomNodeType>();

Notes

  • This hook was created to make prototyping easier and our documentation examples clearer. Although it is OK to use this hook in production, in practice you may want to use a more sophisticated state management solution like Zustand instead.