0% found this document useful (0 votes)
4 views48 pages

React Flow

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views48 pages

React Flow

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

Introduction & Basics

Q1. What is React Flow?


React Flow is a React library that helps to build node-based editors and flow diagrams. It
allows you to easily create things like workflow builders, mind maps, or automation
flows using draggable nodes and edges.

Q2. Why is React Flow used in React projects?


React Flow is used because it saves a lot of time for building visual editors. Instead of
writing complex logic for drawing lines, moving nodes, and handling events, React Flow
gives ready-made components that make everything smooth and professional.

Q3. What type of applications can you build using React Flow?
You can build many types of apps such as workflow builders, chatbot flows, automation
tools, data pipelines, and visual editors. Basically, it’s useful wherever users need to
connect steps visually.

Q4. Is React Flow a library or a framework?


React Flow is a library, not a framework. It provides pre-built React components and
hooks that make it easy to add flow-based features inside your React app.

Q5. Which programming language is React Flow built with?


React Flow is built using JavaScript and TypeScript. It’s fully compatible with modern
React syntax like hooks and functional components.

Q6. How does React Flow help in visualizing data or workflows?


React Flow helps by displaying data or processes as nodes and edges. This visual format
makes it easy to understand how different parts of a system are connected and how data
flows between them.

Q7. What problem does React Flow solve for developers?


It solves the difficulty of creating interactive flow diagrams from scratch. Normally,
developers have to handle dragging, zooming, connecting, and updating manually —
React Flow takes care of all that automatically.

Q8. How does React Flow differ from plain HTML canvas or SVG diagrams?
With plain HTML canvas or SVG, you need to manually draw shapes and manage all
events. React Flow already provides node management, connection handling, zoom, and
panning out of the box — saving a lot of effort.

Q9. Does React Flow depend on React to work?


Yes, React Flow depends completely on React. It’s made using React components and
hooks, so you can’t use it directly with other frameworks like Vue or Angular.
Q10. What version of React is compatible with the latest React Flow?
The latest React Flow works best with React 18 or higher. It supports all modern React
features like concurrent rendering and hooks.

Q11. Can you use React Flow in a [Link] project?


Yes, React Flow works perfectly with [Link]. Since [Link] supports React components,
you can easily integrate React Flow for creating visual workflows, dashboards, or
automation builders inside your [Link] app.

Q12. Is React Flow open source?


Yes, React Flow is an open-source library. It’s free to use and available on GitHub, where
developers can contribute, report bugs, or suggest new features.

Q13. What company or developers maintain React Flow?


React Flow is maintained by a company called wbkd, a German software team known for
creating open-source React tools and libraries.

Q14. What are some popular apps built using React Flow?
React Flow is used in many apps like n8n, Zapier-like workflow tools, AI pipeline editors,
chatbot builders, and automation dashboards where users connect steps visually.

Q15. How is React Flow different from libraries like GoJS or [Link]?
GoJS and [Link] are more low-level and need more manual coding. React Flow is React-
specific and provides pre-built React components for flows, making it faster and easier to
build interactive editors with less code.

Q16. What are the main building blocks of React Flow?


The main building blocks are nodes, edges, and the ReactFlow component. Nodes
represent items or steps, edges connect them, and the ReactFlow component renders
everything inside a canvas-like area.

Q17. What is a node in React Flow?


A node is like a box or block that represents one element in your flow — for example, a
task, a message, or a process step. Each node can have data, labels, and connection
points.

Q18. What is an edge in React Flow?


An edge is a connection line that links two nodes together. It shows how one step flows
into another, helping users understand relationships or data movement in a process.

Q19. What do we mean by “flow” in React Flow?


“Flow” refers to the complete network of nodes and edges that together form a visual
process or diagram. It’s basically how all parts connect and move from one point to
another.
Q20. How does React Flow render nodes on the screen?
React Flow renders nodes using SVG elements inside a React canvas. Each node is
treated as a React component, which makes it easy to customize its design, position, and
behavior dynamically.

Q21. Can React Flow handle interactive workflows?


Yes, React Flow is made for interactive workflows. Users can drag, connect, and update
nodes in real time. It also supports features like zoom, panning, and dynamic data
updates, making workflows feel smooth and responsive.

Q22. What is the relationship between React Flow and React state?
React Flow uses React state to manage everything — like the position of nodes, edges,
and user interactions. You can use React hooks such as useState or useNodesState to
track and update the diagram in real time.

Q23. Is React Flow only for visual diagrams?


No, React Flow is not just for visual diagrams. It’s used for data flows, logic editors,
chatbot builders, and workflow automation tools — anywhere you need visual
connections between components.

Q24. What are common use cases of React Flow?


React Flow is commonly used in workflow builders, automation tools like Zapier,
chatbot design tools, AI pipeline editors, data visualization dashboards, and logic flow
apps.

Q25. What is a “graph” in React Flow terms?


A graph is the complete structure of nodes and edges in your flow. It represents all
connected elements and their relationships — basically, the full visual layout of your
diagram.

Q26. Does React Flow support both horizontal and vertical layouts?
Yes, React Flow supports both. You can manually set the layout direction or use layout
libraries like Dagre or [Link] to automatically arrange nodes horizontally or vertically.

Q27. How does React Flow handle drag and drop behavior?
React Flow has built-in drag-and-drop support. You can move nodes around freely,
connect them using handles, and even create new nodes by dragging from an external
sidebar.

Q28. What is the smallest React Flow setup you can make?
The smallest setup includes just one ReactFlow component with a nodes array and an
edges array. With these two, you can render a simple diagram with a few connected
boxes.
Q29. How does React Flow handle zooming and panning?
React Flow automatically supports zooming and panning. You can use your mouse wheel
or touch gestures to zoom in/out and click-drag to move around the canvas smoothly.

Q30. Can you integrate React Flow with Redux or Zustand?


Yes, you can easily integrate React Flow with Redux, Zustand, or any state management
library. This helps when you want to save flows globally, sync data between pages, or
share state across multiple components.

2. Setup & Installation

Q31. How do you install React Flow in a React project?


You can install React Flow just like any other React library. Open your terminal inside the
project folder and run the npm or yarn command to add it as a dependency.

Q32. What command is used to install React Flow using npm?


To install with npm, use this command:
npm install reactflow
This will download and add React Flow to your project’s node_modules.

Q33. How do you install React Flow using yarn?


If you’re using Yarn, the command is:
yarn add reactflow
It does the same job — adds React Flow to your project for use in your components.

Q34. Do you need to install any peer dependencies for React Flow?
Usually, no extra peer dependencies are required, but you must have React 18 or newer
already installed in your project since React Flow depends on it.

Q35. How do you import React Flow into a component?


You can import it like this:
import ReactFlow from 'reactflow';
Then you can use <ReactFlow /> inside your component’s JSX.

Q36. What is the default export of the React Flow package?


The default export is the ReactFlow component, which is the main component
responsible for rendering the flow chart on screen.

Q37. What does the <ReactFlow /> component do?


The <ReactFlow /> component handles rendering of nodes, edges, zooming, panning,
and interactions on the canvas. It’s the core visual part of React Flow.
Q38. What props are required to render a simple flow diagram?
To render a basic diagram, you need two props: nodes and edges. Both are arrays — one
for defining your boxes and one for their connections.

Q39. Can React Flow be used in a TypeScript project?


Yes, React Flow is written in TypeScript, so it works perfectly in TypeScript projects and
provides full type definitions for nodes, edges, and events.

Q40. How do you type nodes and edges in TypeScript?


You can import and use the built-in types like this:

import { Node, Edge } from 'reactflow';

Then define them as Node[] and Edge[] to make your flow strongly typed and error-free.

Q41. Do you need any CSS to make React Flow visible?


Yes, React Flow needs some basic CSS to display properly. You must give it a height and
width — otherwise, it won’t be visible on the screen because the canvas has no default
size.

Q42. How do you style React Flow to fit 100% width and height?
You can wrap it in a div with styles like:

<div style={{ width: '100%', height: '100vh' }}>

<ReactFlow nodes={nodes} edges={edges} />

</div>

This makes the flow take full screen space.

Q43. How do you wrap <ReactFlow /> inside a parent div correctly?
Always place <ReactFlow /> inside a div that has a fixed or flexible height. React Flow
uses that container’s size to render its internal canvas properly.

Q44. What prop is used to provide the list of nodes?


The nodes prop is used. You pass an array of node objects to it, each containing
properties like id, position, and data.

Q45. What prop is used to provide the list of edges?


The edges prop is used. It takes an array of edge objects that define how nodes are
connected to each other.

Q46. What prop enables users to connect nodes?


The onConnect prop enables users to connect nodes interactively. It runs whenever a
user drags a connection line between two nodes.
Q47. What is the purpose of the fitView prop?
fitView automatically adjusts the zoom level so all nodes and edges fit nicely inside the
visible area when the flow first loads.

Q48. What does the onConnect prop do?


onConnect is a callback that triggers when a new connection is created. You can use it to
update your edges state and add a new edge dynamically.

Q49. Can React Flow render with no nodes or edges?


Yes, it can. Even if your nodes or edges arrays are empty, React Flow will render an
empty canvas, ready for you to add elements later.

Q50. How do you add a background grid to React Flow?


You can import and use the <Background /> component from React Flow like this:

<ReactFlow nodes={nodes} edges={edges}>

<Background />

</ReactFlow>

It shows a smooth grid behind your flow for better visual alignment.

Q51. What happens if you don’t give each node a unique ID?
React Flow uses IDs to track nodes. If two nodes share the same ID, updates and
selection can break, edges may point to the wrong node, and rendering becomes
unpredictable. Always use unique string IDs.

Q52. How can you debug installation issues with React Flow?
Check the console errors, confirm you’re on React 18+, reinstall deps (rm -rf
node_modules && npm i), ensure you imported [Link], and verify your imports
(import ReactFlow from 'reactflow'). Try a minimal example with small nodes/edges.

Q53. Does React Flow work with React Strict Mode?


Yes. React Flow supports Strict Mode. In development, effects can run twice, so avoid
side effects in render and keep state updates inside proper handlers.

Q54. Is React Flow SSR (Server-Side Rendering) compatible?


React Flow needs the browser DOM, so render it on the client. In [Link], load it with a
dynamic import (ssr: false) or conditionally render after mount to avoid SSR errors.

Q55. How can you install a specific version of React Flow?


Pin the version in your install command, for example:
npm install reactflow@<version> or yarn add reactflow@<version>.

Q56. What should you do if React Flow canvas appears blank?


Give the parent a fixed height/width, import [Link], ensure nodes/edges are
valid arrays, check z-index/overflow styles, and try fitView on load. Look for runtime
errors in the console.

Q57. What is the role of [Link]?


It provides the base styles for nodes, edges, handles, controls, and the canvas. Without
it, many UI parts won’t display correctly.

Q58. Where should [Link] be imported?


Import it once at your app entry (e.g., src/[Link], [Link], or [Link] _app.tsx) before
using <ReactFlow />:
import 'reactflow/dist/[Link]'.

Q59. Can React Flow be installed globally?


No. Install it per project as a dependency. Global installs won’t make it available to your
app’s bundler.

Q60. How do you update React Flow to the latest version?


Run npm install reactflow@latest (or yarn up reactflow). Review release notes, fix any
breaking changes, and retest your flows.

3. Core Concepts

Q61. What are nodes in React Flow?


Nodes are the main building blocks in React Flow. They represent elements or steps in a
process, such as tasks, messages, or logic blocks, and can be connected to other nodes
using edges.

Q62. What data structure is used to store nodes?


Nodes are stored in a JavaScript array. Each node in the array is an object that includes
an id, type, position, and data.

Q63. What are edges in React Flow?


Edges are the connecting lines between nodes. They show the relationship or flow
between two steps, such as “from node A to node B.”

Q64. What data structure is used to store edges?


Edges are also stored in a JavaScript array. Each edge is an object with properties like id,
source, target, and type.

Q65. What is a handle in React Flow?


A handle is a connection point on a node that allows users to connect it to other nodes.
Handles define where edges can start or end.
Q66. What are the two main types of handles?
The two types of handles are source and target.

 A source handle sends out connections.

 A target handle receives incoming connections.

Q67. How are nodes and edges related?


Nodes are the main elements, and edges connect them. Each edge’s source and target
values refer to the id of the nodes it connects.

Q68. Can you create a node without handles?


Yes, you can. A node without handles simply won’t allow connections, but it will still
display visually — useful for display-only nodes like info boxes or labels.

Q69. How do you identify each node uniquely?


Each node must have a unique id string. This id helps React Flow track, update, and
connect nodes correctly.

Q70. What is the id property in nodes and edges?


The id property is a unique identifier used to distinguish one node or edge from another.
It’s required for React Flow to handle updates, connections, and rendering accurately.

Q71. What is the type property in a node object?


The type property defines the style or component used to render the node. For
example, you can have a "default", "input", "output", or even a custom node type that
you create for special designs or logic.

Q72. What is the data property used for in nodes?


The data property stores custom information related to that node. You can pass
anything inside — like text, labels, icons, or even functions — and access it inside your
custom node component.

Q73. What is the purpose of the source and target properties in edges?
The source property tells React Flow which node an edge starts from, and the target
property tells which node it connects to. Together, they define the direction of the
connection.

Q74. What does the position property define in a node?


The position property defines the exact x and y location of a node on the canvas. It
controls where the node appears visually in the flow diagram.

Q75. Can a node have multiple handles?


Yes, a node can have multiple handles. You can add several source and target handles to
one node if it needs to connect to multiple other nodes.
Q76. Can two nodes have the same ID?
No, every node must have a unique ID. If two nodes share the same ID, React Flow will
get confused and may render or connect them incorrectly.

Q77. What happens if two edges have the same ID?


Just like nodes, edges also need unique IDs. If two edges have the same ID, React Flow
might overwrite or skip one of them, causing broken or missing connections.

Q78. How does React Flow detect connections?


React Flow detects connections through handles. When a user drags from a source
handle to a target handle, React Flow triggers the onConnect event with the source and
target node IDs.

Q79. Can you make a circular connection (node connecting to itself)?


Yes, it’s technically possible. You can connect a node’s source handle to its own target
handle, creating a self-loop connection — useful in some logic flow designs.

Q80. What is the default node type if you don’t specify one?
If you don’t specify a type, React Flow automatically uses the “default” node type, which
is a basic rectangular node with built-in connection handles.

Q81. How do you define a custom node type?


To define a custom node type, first create a React component for your node’s UI. Then,
pass it inside the nodeTypes prop of <ReactFlow /> like this:

const nodeTypes = { customNode: CustomNode };

<ReactFlow nodes={nodes} edges={edges} nodeTypes={nodeTypes} />

Now you can use type: "customNode" in any node object.

Q82. What is the difference between sourceHandle and targetHandle?


sourceHandle is the handle ID where an edge starts, and targetHandle is the handle ID
where it ends. They’re used when a node has multiple handles to know which exact
point is connected.

Q83. Can you have multiple edges between the same nodes?
Yes, you can. React Flow allows multiple edges between the same two nodes as long as
their edge IDs are unique. This is useful for showing different types of relationships or
data flows.

Q84. What are edge labels used for?


Edge labels are text or icons shown along the connection line. They help users
understand the meaning of a connection — for example, “Yes / No,” “True / False,” or
data types like “Input” or “Output.”
Q85. How do you add labels to edges?
You can add labels by including a label property in the edge object like this:

{ id: 'e1-2', source: '1', target: '2', label: 'Send Data' }

React Flow automatically displays the label along that edge.

Q86. What is the default edge type?


The default edge type is “bezier”, which draws a curved line between the source and
target nodes for a smooth visual flow.

Q87. What is a straight edge?


A straight edge connects nodes with a simple straight line. It’s often used when you
want a clean, direct connection without curves.

Q88. What is a smoothstep edge?


A smoothstep edge creates a curved but cleaner and smoother transition between
nodes. It bends softly at both ends and looks modern and readable.

Q89. What is a bezier edge?


A bezier edge is a curved edge that uses Bezier curves to connect nodes. It’s the most
common type and makes the diagram look natural and flowing.

Q90. What is a step edge?


A step edge connects nodes using 90-degree turns, creating a boxy look. It’s useful for
logic diagrams or when you want a clear, structured connection path.

Q91. Which property controls edge style?


Use the type property to choose the shape (bezier, smoothstep, step, straight). For visual
styling like color or width, use the style prop (e.g., { stroke, strokeWidth }) and
markerEnd/markerStart for arrowheads.

Q92. Can edges be directional in React Flow?


Yes. Edges are logically directional (source → target). You can show direction visually by
adding arrowheads using markerEnd (and markerStart if needed).

Q93. Can edges be clickable?


Yes. Handle clicks with the onEdgeClick callback on <ReactFlow />. You can also use
onEdgeMouseEnter/onEdgeMouseLeave for hover effects.

Q94. How do you define the position of a node on the canvas?


Set the node’s position: { x, y } in pixels. React Flow uses this top-left coordinate to place
the node on the viewport.

Q95. How do you center all nodes in view?


Call fitView() from useReactFlow() or set the fitView prop on <ReactFlow /> so it auto-
zooms to include all nodes on initial render.
Q96. What is the fitView function used for?
fitView() calculates bounds of all nodes and adjusts zoom/pan so everything is neatly
visible with padding—great after loading or changing layouts.

Q97. How do you prevent nodes from being draggable?


Globally set nodesDraggable={false} on <ReactFlow />, or per node set draggable: false.
This locks node positions.

Q98. Can you disable connecting nodes?


Yes. Use nodesConnectable={false} to turn off connections globally, remove/hide
handles, or validate with isValidConnection to allow only certain links.

Q99. What is the role of onNodeClick?


It fires when a node is clicked and gives you the event and node data. Use it to select,
open side panels, edit details, or focus the camera.

Q100. How do you handle edge click events?


Provide an onEdgeClick handler to <ReactFlow />. In the callback, you get the event and
the clicked edge—use it to select, edit label, delete, or highlight the edge.

4. Node Types & Custom Nodes

Q101. What is a custom node in React Flow?


A custom node is a user-defined React component that replaces the default node
design. It lets you build your own UI and behavior, like adding buttons, icons, inputs, or
dynamic content inside the node.

Q102. How do you define a custom node component?


You can create a simple React component that accepts data and id as props. For
example:

function CustomNode({ data }) {

return <div className="custom-node">{[Link]}</div>;

This becomes your visual node component.

Q103. How do you register custom node types?


You create an object where keys are type names and values are your custom
components, then pass it to the nodeTypes prop of <ReactFlow />.
Q104. What prop is used to register node types?
The nodeTypes prop is used. For example:

const nodeTypes = { customNode: CustomNode };

<ReactFlow nodeTypes={nodeTypes} />

Q105. Can a node type be dynamic?


Yes. You can dynamically choose a node’s type by changing the type property in the node
object. React Flow will automatically render the correct component for that node type.

Q106. How do you pass custom data to a node?


You pass data using the data property inside the node object. For example:

{ id: '1', type: 'customNode', position: {x: 0, y: 0}, data: { label: 'Hello' } }

Q107. What is the data prop inside a custom node used for?
The data prop carries all the custom information for that node — like text, color, inputs,
or event handlers. It lets each node have its own unique behavior or content.

Q108. How do you access node data in the custom node component?
In your custom node component, React Flow automatically provides the data prop. You
can directly access it like:

function CustomNode({ data }) {

return <div>{[Link]}</div>;

Q109. Can you use React hooks inside a custom node component?
Yes, you can. Since a custom node is a normal React component, you can freely use
hooks like useState, useEffect, or even useReactFlow() to control behavior or trigger
updates.

Q110. How do you define input and output handles?


You use the <Handle /> component from React Flow inside your custom node. For
example:

<Handle type="target" position="top" />

<Handle type="source" position="bottom" />

The type defines whether it’s an input (target) or output (source), and position sets
where it appears on the node.

Q111. What is the purpose of the <Handle /> component?


The <Handle /> component defines connection points on a node. It tells React Flow
where users can start or end connections between nodes — like plug-in points for edges.
Q112. What are valid handle types?
There are two handle types:

 source — where a connection starts (output).

 target — where a connection ends (input).

Q113. What does the position prop do in <Handle />?


The position prop defines where the handle appears on the node — possible values are
top, right, bottom, or left. It decides the direction of connections visually.

Q114. How do you prevent certain handles from connecting?


You can control this using the isValidConnection prop on <Handle />. It’s a function that
returns true or false based on your custom logic — for example, disallowing certain node
types from connecting.

Q115. What is the isConnectable prop used for?


The isConnectable prop enables or disables the connection feature for a handle. If set to
false, users can’t make or drop connections on that handle.

Q116. Can you style handles?


Yes, handles can be styled using the style prop or CSS classes. You can control size, color,
border, or even hover effects.

Q117. How do you change handle color or shape?


Use inline styles or custom CSS. For example:

<Handle type="source" position="bottom" style={{ background: 'red', borderRadius:


'50%' }} />

This creates a red, circular handle.

Q118. How do you disable drag inside a custom node?


You can set the attribute onDragStart={(e) => [Link]()} on elements inside
the node. This prevents dragging when clicking or interacting with those inner elements.

Q119. Can you include icons or images inside a node?


Yes. Since a custom node is a normal React component, you can add icons, images, or
even other React components like buttons or dropdowns inside it.

Q120. How do you resize custom nodes?


You can control size using CSS or inline styles (e.g., width and height). For dynamic
resizing, you can use useEffect or libraries like react-resizable to update node dimensions
programmatically.

Q121. How do you conditionally render handles?


Use normal React conditional rendering inside your custom node. For example, check
[Link] and render <Handle type="source" ... /> only when it’s true. You can
also toggle isConnectable or use isValidConnection for finer control.

Q122. What happens if a node type is missing?


If a node’s type isn’t found in nodeTypes, React Flow falls back to the default node (and
may warn in the console). Your flow still renders, but that node won’t use your custom
UI.

Q123. How can you dynamically change a node type?


Update the node in state. Use setNodes(prev => [Link](n => [Link] === id ? { ...n, type:
'myNewType' } : n)). React Flow re-renders that node with the new component instantly.

Q124. Can you have nested components inside a custom node?


Yes. A custom node is a normal React component, so you can nest buttons, inputs,
menus, tabs—anything. Just stop event propagation on draggable areas when needed.

Q125. How do you pass node data updates from parent to child?
Keep nodes in parent state. When something changes, call setNodes to update the
node’s data ({ ...n, data: { ...[Link], title } }). The updated data automatically flows into
the custom node component.

Q126. How do you trigger state updates when a node changes?


Use React Flow callbacks like onNodesChange, onEdgesChange, and onConnect. In
custom nodes, you can call const { setNodes } = useReactFlow() and update that node
directly (e.g., on input change).

Q127. Can custom nodes include event handlers?


Absolutely. Attach handlers like onClick, onChange, onKeyDown to elements inside your
node. For drag-sensitive areas, use onMouseDown={(e) => [Link]()} to avoid
moving the node.

Q128. How do you make a custom node clickable?


Add onClick to the node’s root element or use the global onNodeClick prop on
<ReactFlow />. If you use an internal onClick, consider [Link]() so it doesn’t
conflict with canvas interactions.

Q129. How can you show tooltips on nodes?


Quick way: use the title attribute on an element. For richer UI, use a tooltip library (e.g.,
Headless UI, Radix, or a small custom component) and show it on hover/focus inside
your node.

Q130. How do you use Tailwind or CSS Modules in node styling?


For Tailwind, add classes to your node JSX (e.g., className="rounded-lg p-3 shadow").
For CSS Modules, import styles and use className={[Link]}. Both work fine
alongside [Link] for base styles.
Q131. Can you use Material UI components inside a node?
Yes. A custom node is a normal React component, so you can use MUI buttons, cards,
menus, etc. Just stop canvas dragging on interactive parts ([Link]() on mouse
down) to avoid accidental node moves.

Q132. What is the difference between static and dynamic node data?
Static data doesn’t change after render (e.g., a fixed label). Dynamic data updates at
runtime (e.g., status, counts). Store it in data and update via setNodes so the node re-
renders.

Q133. Can you render a node based on external API data?


Yes. Fetch data in the parent (or with React Query/SWR), then pass results into the node
via data. Show loading/error states in the node UI. Avoid heavy fetching directly inside
the node component.

Q134. How do you handle conditional colors based on data?


Compute a class/style from data and apply it: for example, [Link] === 'error' ? 'bg-
red-500' : 'bg-green-500', or inline styles like { background: [Link] }.

Q135. Can custom nodes have multiple inputs or outputs?


Yes. Add multiple <Handle type="target" ... /> (inputs) and <Handle type="source" ... />
(outputs). Give each a unique id when you need to target specific handles.

Q136. What is the role of node dimensions in layout?


Node width/height affect auto-layout spacing, edge routing, collision/overlap, and how
fitView() frames the graph. Accurate dimensions make the diagram readable.

Q137. Can you programmatically change node size?


Yes. Change styles based on data or state, and if size changes after mount, call
useUpdateNodeInternals(nodeId) to let React Flow recalc edges/handles correctly.

Q138. How do you add background color to a node?


Style the node’s root element (Tailwind class or inline style):
<div className="bg-slate-100 p-3 rounded">...</div> or <div style={{ background:
'#f5f5f5' }}>.

Q139. Can you change node cursor style on hover?


Yes. Use CSS on the node wrapper or handles (e.g., .node:hover { cursor: pointer; }).
Inline styles also work: { cursor: 'grab' } and { cursor: 'grabbing' } while dragging.

Q140. What is the best way to organize multiple custom node types?
Create one component per node type, keep them in a nodes/ folder, export a single
nodeTypes map, and define shared TypeScript interfaces for data. Co-locate small
CSS/Tailwind utilities and keep handle IDs consistent across types.
5. Edges & Connections

Q141. How are edges created between nodes?


Edges are created either interactively (dragging from a source handle to a target handle
in the UI) or programmatically by adding an edge object to your edges array in state.
Most apps combine both: user draws, you save it.

Q142. What triggers the onConnect event?


onConnect fires when a user finishes a valid drag from a source handle to a target
handle. React Flow passes a connection object (with source, target, and optional handle
IDs) so you can add a new edge to state.

Q143. How do you define an edge manually?


Push a new object into the edges array, for example:

setEdges((eds) => [...eds, { id: 'e1-2', source: '1', target: '2' }]);

You can include extras like type, label, animated, and style.

Q144. What is the structure of an edge object?


An edge is an object with at least id, source, and target. Common optional fields:
sourceHandle, targetHandle, type (bezier, smoothstep, step, straight), label, animated,
style, markerEnd.

Q145. What properties define an edge connection?


source and target define which nodes are connected. sourceHandle and targetHandle
(optional) define which handles on those nodes are used. Together they fully describe
the link.

Q146. How do you prevent certain nodes from connecting?


Use connection validation. Either set isConnectable={false} on specific handles, or
implement isValidConnection to reject links based on your rules (node types, handle IDs,
directions, etc.).

Q147. What does isValidConnection do?


It’s a predicate that receives the attempted connection and returns true/false. If it
returns false, React Flow blocks that connection. This is the main way to enforce custom
linking rules.

Q148. How do you validate connections dynamically?


Write logic inside isValidConnection that checks the runtime context—e.g., node types,
max-children limits, preventing cycles, or disallowing self-links. You can also read external
state (like Redux/Zustand) for live rules.
Q149. Can you connect multiple edges from one output handle?
Yes. By default, one source handle can feed many edges. If you need to restrict it (e.g.,
only one output), enforce it in isValidConnection by counting existing edges from that
handle.

Q150. Can you connect multiple inputs to a single node?


Yes. A node can have many incoming edges (even to the same target handle, unless you
block it). Use validation to limit the number or to require specific handle pairs if your
design needs it.

Q151. What are edge markers?


Edge markers are arrowheads or symbols drawn at the start or end of an edge to show
direction or meaning, like an arrow pointing from source to target.

Q152. How do you add arrow markers to edges?


Add a markerEnd (or markerStart) to the edge. For example:

import { MarkerType } from 'reactflow';

{ id:'e1-2', source:'1', target:'2', markerEnd:{ type: [Link] } }

This draws an arrow at the end of the edge.

Q153. How do you style an edge with custom color?


Use the style property on the edge:

{ ..., style:{ stroke:'#4f46e5' } }

You can also set [Link] to match the arrow color.

Q154. Can edges have custom components?


Yes. Define custom edge components and register them with edgeTypes. Then set type
on your edge (e.g., type:'fancyEdge') to render that component.

Q155. How do you define edge labels?


Add a label property to the edge object:

{ id:'e1-2', source:'1', target:'2', label:'Send Data' }

React Flow renders the text along the edge.

Q156. Can edge labels be interactive?


Yes. Use a custom edge or the EdgeLabelRenderer to render React elements (buttons,
inputs) so users can click or edit directly on the label.

Q157. What is an animated edge?


An animated edge shows a moving stroke effect, making the direction of flow obvious
(great for streaming data or active pipelines).
Q158. How do you make an edge animated?
Set animated: true on the edge object:

{ ..., animated:true }

React Flow handles the animation automatically.

Q159. How do you change the width of an edge line?


Set strokeWidth inside the edge style:

{ ..., style:{ strokeWidth:2 } }

Q160. What happens if you connect incompatible handles?


React Flow only connects source → target. If you try source→source or target→target,
the connection is rejected. If you add custom rules with isValidConnection and they fail,
the edge won’t be created.

Q161. How do you delete an edge programmatically?


Update your edges state and remove it by id, e.g.:

setEdges((eds) => [Link]((e) => [Link] !== 'e1-2'));

You can also use useReactFlow().setEdges to replace the whole list.

Q162. How do you prevent self-connections?


Validate in isValidConnection and reject when source === target:

const isValidConnection = (c) => [Link] !== [Link];

Q163. Can edges be directional?


Yes. They’re logically source → target. Add arrowheads with markerEnd (e.g.,
[Link]) to show direction visually.

Q164. How do you add hover effects to edges?


Track hover with onEdgeMouseEnter/Leave and update style in state, or use a custom
edge that changes its class/style on hover.

Q165. How do you make edges dashed or dotted?


Set strokeDasharray in the edge style, e.g.:

{ style: { strokeDasharray: '6 3' } }

Q166. Can you update edge properties dynamically?


Yes. Map over edges and update the target edge:

setEdges((eds) => [Link](e => [Link] === id ? { ...e, animated: true } : e));

Q167. How do you listen for edge updates?


Use onEdgesChange for add/remove/update changes, and onEdgeUpdate (plus
onEdgeUpdateStart/End) when the user reconnects an existing edge between handles.
Q168. How do you detect when an edge is deleted?
Use onEdgesDelete to get the deleted edges directly, or handle a [Link] ===
'remove' inside onEdgesChange.

Q169. What is the difference between onEdgesChange and onConnect?


onConnect fires once when a new edge is created by the user.
onEdgesChange fires for mutations to existing edges (add, remove, select, update).

Q170. How do you detect when two nodes are connected?


Handle onConnect. It gives { source, target, sourceHandle, targetHandle }. In the handler,
add the edge to state and run any side effects you need.

Q171. How do you create a default edge style?


Use the defaultEdgeOptions prop on <ReactFlow /> to set shared options like type,
animated, style, and markerEnd. All new/rendered edges inherit these defaults unless
they override them.

Q172. Can you use gradient colors on edges?


Yes, but use a custom edge that draws an SVG path with a
<defs><linearGradient/></defs> and references it via stroke="url(#gradId)". Built-in
edges only support solid stroke.

Q173. What is the best way to handle edge IDs?


Make them unique and stable. A simple pattern is e-${source}-${target}-${nanoid()}
when adding edges, so updates/deletes are reliable and no ID collisions happen.

Q174. Can you render edges behind or above nodes?


By default, edges render behind nodes. To draw UI above nodes (labels, buttons), use
EdgeLabelRenderer or a custom edge that portals interactive elements with higher
stacking.

Q175. How do you prevent overlapping edges?


Use edge types that route cleanly (step, smoothstep) or a custom edge that offsets
parallel paths. Auto-layout libraries (Dagre/ELK) help reduce crossings by spacing nodes
better.

Q176. How do you programmatically connect two nodes?


Add an edge to state (or use addEdge):

setEdges((eds) => addEdge({ id:'e1-2', source:'1', target:'2' }, eds));

Include sourceHandle/targetHandle if needed.

Q177. What is the difference between connecting nodes manually and via code?
Manual connections fire onConnect from a user drag. Programmatic connections skip
the drag and directly mutate state, so you control IDs, handles, and timing yourself.
Q178. How do you remove all edges at once?
Set the edges array to empty: setEdges([]). If you also reset selections or history, do that
in the same update.

Q179. Can edges connect to multiple targets simultaneously?


A single edge connects one source to one target. To fan out, create multiple edges from
the same source/handle to different targets.

Q180. What is a floating edge in React Flow?


A floating edge is a custom edge that auto-anchors to the closest points on node bounds
(not fixed handles). It recalculates while nodes move, keeping connections visually neat.

6. Hooks & State Management

Q181. What is useNodesState hook used for?


useNodesState manages your nodes as React state. It gives you the current nodes array,
a setter to update nodes, and a change handler that you pass to <ReactFlow /> so drag,
select, and position updates sync automatically.

Q182. What is useEdgesState hook used for?


useEdgesState does the same for edges. It stores your edges array, lets you update it,
and provides a change handler that keeps UI actions (add/remove/update) in sync with
your React state.

Q183. What is useReactFlow hook used for?


useReactFlow gives you imperative helpers for the canvas: fitView, project,
screenToFlowPosition, addNodes, addEdges, setNodes, setEdges, deleteElements,
updateNodeInternals, setViewport, and more—great for programmatic control.

Q184. How do these hooks simplify managing nodes and edges?


They remove boilerplate. Instead of manually wiring event logic, you pass the provided
onNodesChange/onEdgesChange to <ReactFlow />, and user actions update your state
safely and predictably.

Q185. How do you use useNodesState in a component?


Initialize with default nodes, then pass handlers to <ReactFlow />:

const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);

<ReactFlow nodes={nodes} onNodesChange={onNodesChange} />

Q186. What values does useNodesState return?


It returns a tuple: [nodes, setNodes, onNodesChange].
Q187. What values does useEdgesState return?
It returns a tuple: [edges, setEdges, onEdgesChange].

Q188. How do you update a node’s position using state hooks?


Either let React Flow handle it via onNodesChange, or update manually:

setNodes(ns => [Link](n => [Link] === '1' ? { ...n, position: { x: 200, y: 120 } } : n));

Call updateNodeInternals('1') from useReactFlow() if handles/layout depend on size.

Q189. How do you update edge data using hooks?


Map and modify the target edge, then set:

setEdges(es => [Link](e => [Link] === 'e1-2' ? { ...e, label: 'Updated', data: { ...[Link],
status: 'ok' } } : e));

You can also react to user changes via onEdgesChange.

Q190. What is the purpose of setNodes function?


setNodes replaces or updates the nodes state. Use it to add, remove, or edit nodes
(labels, type, position) using a safe functional update so changes are batched and
consistent.

Q191. What is the purpose of setEdges function?


setEdges updates your edges state. Use it to add, remove, or edit edges (labels, style,
markers, animation). Prefer the functional form setEdges((es) => ...) so updates are safe
and batched.

Q192. How do you remove a node using setNodes?


Filter it out by id:

setNodes((ns) => [Link]((n) => [Link] !== '1'));

If needed, also remove edges connected to that node using setEdges so your graph stays
consistent.

Q193. How do you append a new node to existing state?


Push a new node with a functional update:

setNodes((ns) => [...ns, { id: '3', position:{ x:200, y:150 }, data:{ label:'New' } }]);

Q194. What does onNodesChange do?


onNodesChange processes UI-driven node changes (drag, select, add, remove). Pass it to
<ReactFlow /> and it will keep your nodes state in sync without manual bookkeeping.

Q195. What does onEdgesChange do?


onEdgesChange handles edge mutations from the UI (create, delete, select, reconnect).
When passed to <ReactFlow />, it updates your edges state accordingly.
Q196. What is the purpose of the addEdge utility function?
addEdge helps you append a correctly shaped edge (with id, source, target, optional
type, label, etc.) to your current edges array. It also guards against common mistakes.

Q197. How do you import addEdge?


Import it from React Flow:

import { addEdge } from 'reactflow';

Q198. How do you use addEdge with onConnect?


Use onConnect to capture user-drawn connections and then call addEdge:

const onConnect = useCallback(

(params) => setEdges((es) => addEdge(params, es)),

[]

);

This adds the new edge to state immediately.

Q199. Can you store flow state in Redux or Zustand?


Yes. Keep nodes and edges in Redux/Zustand and pass them into <ReactFlow />. Wire
onNodesChange/onEdgesChange to dispatch or set store state so UI and store stay
synced.

Q200. How do you synchronize React Flow state with external data?
Load data from your API/store, map it to nodes/edges, and set state. On user changes,
persist back via debounced saves or explicit “Save” actions. Use stable IDs, and consider
useEffect to rehydrate when external data updates.

Q201. Can you trigger a re-render from outside the flow?


Yes. Keep nodes and edges in React state (or Redux/Zustand) and update them with
setNodes/setEdges. Any change there re-renders the canvas. From outside, use
useReactFlow() (inside a provider) to call setNodes, setEdges, or setViewport, which also
triggers a re-render.

Q202. How do you reset the entire graph state?


Clear state and reset the camera:

setNodes([]);

setEdges([]);

const { setViewport } = useReactFlow();

setViewport({ x: 0, y: 0, zoom: 1 });

Optionally repopulate with your initial nodes/edges and call fitView().


Q203. How do you get the current viewport using useReactFlow?
Call const { getViewport } = useReactFlow(); then const vp = getViewport();. You’ll get { x,
y, zoom } representing the current pan and zoom.

Q204. How do you zoom programmatically using useReactFlow?


Use the instance helpers: zoomIn(), zoomOut(), or zoomTo(1.5) for an absolute zoom
level. You can also setViewport({ x, y, zoom }) for full control.

Q205. How do you fit view using a hook?


Call const { fitView } = useReactFlow(); then fitView({ padding: 0.2 }). It computes bounds
of all nodes and adjusts pan/zoom so everything is visible.

Q206. Can you access nodes directly from useReactFlow?


Yes. Use getNodes() and getEdges() to read the current graph, and setNodes() /
setEdges() / addNodes() / addEdges() to modify it.

Q207. What is toObject() method in React Flow instance?


toObject() returns a serializable snapshot of the flow: { nodes, edges, viewport }. It’s
ideal for saving/restoring diagrams to a database or local storage.

Q208. How do you get all selected nodes?


Use getNodes().filter(n => [Link]) from useReactFlow(). Alternatively, handle
onSelectionChange which gives you { nodes, edges } that are currently selected.

Q209. How do you clear selections?


Programmatically unselect everything:

setNodes(ns => [Link](n => ({ ...n, selected: false })));

setEdges(es => [Link](e => ({ ...e, selected: false })));

This removes selection from all elements.

Q210. How do you find a node by its ID?


Use const node = useReactFlow().getNode('your-id');. If you’re not using the instance,
search your state array: [Link](n => [Link] === 'your-id').

Q211. How do you programmatically move a node?


Update its position in state, then (if size/handles depend on layout) refresh internals:

setNodes(ns => [Link](n => [Link] === '1' ? { ...n, position: { x: 300, y: 160 } } : n));

useReactFlow().updateNodeInternals('1');

Q212. Can you combine useReactFlow with useState?


Yes. Keep nodes/edges in useState (or Redux/Zustand) and also call instance helpers
(e.g., fitView, setViewport) from useReactFlow() for camera and graph ops. They work
together smoothly.
Q213. What is the role of onInit in React Flow?
onInit runs when the canvas is ready and gives you the React Flow instance. Use it to
store the instance, set initial viewport, call fitView(), or wire custom shortcuts.

Q214. How do you access the flow instance in onInit?


Provide a handler:

const onInit = (instance) => {

[Link]();

// [Link](), [Link](...), etc.

};

<ReactFlow onInit={onInit} ... />

Q215. Can you store the flow instance in a ref?


Yes.

const rfRef = useRef(null);

const onInit = (inst) => ([Link] = inst);

// later: [Link]?.fitView();

A ref avoids re-renders when you read/call methods.

Q216. How do you export current flow data as JSON?


Use the instance snapshot:

const { toObject } = useReactFlow();

const json = [Link](toObject()); // { nodes, edges, viewport }

Send this to your API or download as a file.

Q217. How do you restore flow from JSON?


Parse and set state, then fit view:

const data = [Link](jsonFromDB);

setNodes([Link] || []);

setEdges([Link] || []);

useReactFlow().setViewport([Link] || { x:0, y:0, zoom:1 });

Q218. How do you save flow to local storage?


Serialize on demand:

const save = () => {


const snap = useReactFlow().toObject();

[Link]('flow', [Link](snap));

};

Q219. How do you update local storage when flow changes?


Debounce inside an effect tied to nodes/edges/viewport, or use
onNodesChange/onEdgesChange/onMoveEnd to persist:

useEffect(() => {

const snap = [Link]();

[Link]('flow', [Link](snap));

}, [nodes, edges, viewport]); // with debouncing

Q220. How do you prevent unnecessary re-renders when using these hooks?
Use functional state updates, memoize handlers with useCallback, memoize heavy data
with useMemo, store the instance in a ref, and avoid recreating arrays/objects unless
they actually change.

7. Events & Interaction

Q221. What events does React Flow support?


React Flow supports many interactive events like onNodeClick, onEdgeClick,
onNodeDragStart, onNodeDragStop, onConnect, onPaneClick, onPaneScroll, onMove,
onMoveStart, onMoveEnd, onSelectionChange, and more. These let you respond to user
actions inside the canvas.

Q222. What does onNodeClick handle?


onNodeClick triggers when a user clicks on a node. It gives you the event and the node
data. You can use it to select, open details, or perform custom actions like highlighting.

Q223. What does onNodeDragStart do?


onNodeDragStart fires when the user starts dragging a node. It’s useful for showing drag
indicators, saving initial positions, or disabling other UI interactions during movement.

Q224. What does onNodeDragStop do?


onNodeDragStop triggers when a node finishes dragging. You can use it to save the new
position, update your backend, or call updateNodeInternals if layout depends on node
size.
Q225. How do you detect when an edge is clicked?
Use onEdgeClick on <ReactFlow />. It passes the event and the clicked edge object so
you can highlight, edit, or delete that edge.

Q226. What does onPaneClick do?


onPaneClick runs when the user clicks on the empty canvas background (not on nodes or
edges). It’s often used to clear selections or open a “create node” menu.

Q227. What is the difference between pane and node clicks?


A pane click happens when clicking empty space in the flow area, while a node click
happens when clicking on a specific node. Pane clicks don’t trigger node events —
they’re separate for clarity.

Q228. How do you handle double-click events on nodes?


Use onNodeDoubleClick on <ReactFlow />. It’s perfect for actions like renaming, opening
modals, or expanding node details.

Q229. How do you disable dragging of nodes?


Set nodesDraggable={false} on <ReactFlow /> to disable all dragging, or set draggable:
false inside specific node objects for per-node control.

Q230. How do you disable edge creation?


Use nodesConnectable={false} on <ReactFlow /> to block all connections, or hide
handles on specific nodes. You can also conditionally reject links via isValidConnection
returning false.

Q231. How do you handle zoom events?


Use the canvas movement callbacks. onMove fires while the user is zooming or panning,
and onMoveEnd fires when it stops. Read the current { x, y, zoom } via
useReactFlow().getViewport() inside those handlers to react to zoom changes.

Q232. How do you control zoom limits?


Set minZoom and maxZoom props on <ReactFlow />. For example, minZoom={0.5} and
maxZoom={2} to keep users within a sensible zoom range.

Q233. What does the zoomOnScroll prop do?


It toggles mouse-wheel zooming. If zoomOnScroll is true, scrolling the wheel zooms
in/out. If false, the wheel won’t change the zoom level.

Q234. What does the panOnScroll prop do?


It enables panning with the mouse wheel. When panOnScroll is true, wheel scrolling
moves the canvas instead of zooming (useful for trackpads or when zoom is disabled).

Q235. How do you restrict panning to one direction?


Combine panOnScroll with panOnScrollMode="vertical" or "horizontal" to lock the scroll-
pan direction. You can also limit the overall pan area with translateExtent.
Q236. How do you detect when a connection starts?
Handle onConnectStart. It fires when the user begins dragging from a handle, giving you
details like the starting node/handle.

Q237. How do you detect when a connection ends?


Use onConnectEnd to know when the drag finishes, and onConnect to know when a
valid connection was actually created (gives { source, target, ... }).

Q238. How do you handle selection events?


Listen to onSelectionChange. It gives { nodes, edges } currently selected. You can also
react to selection during drags with onMoveStart/End or update UI state (side panels,
toolbars) based on the selection.

Q239. Can you select multiple nodes?


Yes. Multi-select works via box selection (drag on the pane) and modifier-key selection
(e.g., Shift + click). You can customize selection behavior with related props and then
read selected items from onSelectionChange.

Q240. How do you handle keyboard shortcuts with React Flow?


Add your own keydown listeners in your component (or a hotkeys library) and call
instance methods from useReactFlow()—for example, Delete to remove selected
elements, fitView() for F, or custom actions to align nodes or zoom.

Q241. How do you detect when a node is hovered?


Use onNodeMouseEnter and onNodeMouseLeave on <ReactFlow />. They fire with the
event and the hovered node, so you can set local state like hoveredNodeId.

Q242. How do you show a tooltip when hovering over a node?


Track hover with onNodeMouseEnter/Leave, store the node/data in state, and render a
tooltip component near the cursor or node. For a quick option, add title={[Link]}
on an element inside the node.

Q243. How do you change cursor style on drag?


Add CSS for the dragging state (e.g., .react-flow__node.dragging { cursor: grabbing; }) or
toggle a class on onNodeDragStart/Stop. You can also set inline styles on the pane while
moving.

Q244. How do you snap nodes to a grid while dragging?


Enable snapToGrid and set snapGrid={[x, y]} on <ReactFlow />. Nodes will lock to those
grid steps as you drag.

Q245. How do you prevent dropping outside canvas?


Constrain movement with nodeExtent so nodes can’t be positioned outside a rectangle.
Combine with translateExtent to limit panning so the canvas never scrolls past your
bounds.
Q246. How do you reset view on a button click?
Call fitView() from useReactFlow() to auto-frame everything, or setViewport({ x: 0, y: 0,
zoom: 1 }) to return to a fixed camera.

Q247. What does the onMove event do?


onMove fires continuously while the user pans or zooms. Use it for live UI updates, like
showing coordinates or hiding heavy overlays during camera movement.

Q248. What does the onMoveEnd event do?


onMoveEnd fires once after panning/zooming stops. It’s ideal for saving the viewport or
triggering expensive recalculations only after movement finishes.

Q249. How do you make the flow non-interactive (read-only)?


Turn off interactions: nodesDraggable={false}, nodesConnectable={false},
elementsSelectable={false}, zoomOnScroll={false}, panOnDrag={false}. Hide handles if
you don’t want users to see connection points.

Q250. Can you programmatically simulate user drag?


You typically don’t simulate DOM drag. Instead, update state directly (change a node’s
position, use addEdge to connect) or animate the viewport with setViewport/zoomTo for
a smooth, code-driven effect.

8. Customization & Controls

Q251. What is the <Background /> component used for?


The <Background /> component adds a grid or dot pattern behind your nodes and
edges. It helps users align and organize nodes visually, just like a design canvas.

Q252. What types of backgrounds does React Flow support?


React Flow supports two background types — "dots" and "lines". You can choose one
using the variant prop:

<Background variant="lines" />

Q253. How do you change background color?


Use the color prop inside <Background />, for example:

<Background color="#e2e8f0" />

You can also combine it with gap and size props to style spacing and dot size.

Q254. What does the <MiniMap /> component show?


The <MiniMap /> provides a small overview of your entire flow. It displays all nodes and
edges as a scaled-down version, helping users navigate large diagrams easily.
Q255. Can you customize MiniMap node colors?
Yes. You can use the nodeColor prop to dynamically color nodes based on type or data:

<MiniMap nodeColor={(node) => [Link] === 'input' ? 'green' : 'blue'} />

Q256. How do you disable MiniMap interactions?


Set the pannable={false} and zoomable={false} props on <MiniMap />. This makes it a
purely visual reference, not an interactive one.

Q257. What is the <Controls /> component used for?


<Controls /> adds built-in zoom and fit view buttons to the corner of your canvas. It lets
users easily zoom in/out, reset view, or fit everything into view.

Q258. What controls are available by default?


By default, <Controls /> includes:

 Zoom In

 Zoom Out

 Fit View

 Interactive Toggle (lock/unlock movement)

Q259. Can you customize the position of Controls?


Yes. You can use the position prop like position="top-left" or position="bottom-right" to
move the control panel anywhere you want.

Q260. How do you hide zoom controls?


Use individual control props like:

<Controls showZoom={false} />

You can also hide others such as showFitView={false} or showInteractive={false} to keep


only the controls you need.

Q261. How do you style control buttons?


Override the default classes in CSS (e.g., .react-flow__controls and .react-flow__controls-
button) or wrap your own <ControlButton /> with custom classes. You can also pass a
className to <Controls /> and target buttons inside it.

Q262. What are [Link] and Dots?


They are built-in styles for <Background />. Use [Link] for grid lines
and [Link] for dotted paper.

import { Background, BackgroundVariant } from 'reactflow';

<Background variant={[Link]} />


Q263. Can you use custom icons in Controls?
Yes. Hide any built-ins you don’t want and add your own <ControlButton> children with
custom SVGs or icon components.

<Controls showInteractive={false}>

<ControlButton onClick={doThing}>

<MyIcon />

</ControlButton>

</Controls>

Q264. How do you disable panning in Controls?


Disable panning on the canvas, not in Controls: set panOnDrag={false} and
panOnScroll={false} on <ReactFlow />. If needed, also disable zoom
(zoomOnScroll={false}) to make the view static.

Q265. How do you make React Flow responsive?


Place <ReactFlow /> inside a container with responsive height/width (e.g., height: 100%
inside a flex layout or height: 100vh). React Flow observes container size changes
automatically; call fitView() after big layout changes for a clean frame.

Q266. How do you enable dark mode styling?


Toggle dark classes or CSS variables on your app root, then style nodes/edges
accordingly. For the grid, set <Background color={isDark ? '#2a2a2a' : '#e2e8f0'} />.
Tailwind’s dark: variants work well inside custom nodes.

Q267. Can you dynamically change background variant?


Yes. Keep a state like const [variant, setVariant] = useState([Link]) and
pass it to <Background variant={variant} />. Update the state to switch between dots and
lines at runtime.

Q268. How do you change node border color dynamically?


Style based on node data or selection:

<div className={cn('rounded p-2', [Link] ? 'border-red-500' : 'border-slate-300')} />

You can also use the .react-flow__node.selected CSS selector to highlight selected nodes.

Q269. How do you highlight selected nodes visually?


Use the built-in selected class:

.react-flow__node.selected { outline: 2px solid #6366f1; box-shadow: 0 0 0 4px


rgba(99,102,241,.2); }

Or, in a custom node, read the selected prop and change styles conditionally.
Q270. How do you show node count or info overlay on canvas?
Use the <Panel /> helper (or an absolutely positioned div) to render an overlay:

import { Panel } from 'reactflow';

<Panel position="top-right">Nodes: {[Link]}</Panel>

Great for badges, status bars, or live stats.

9. Saving & Loading Flows

Q271. How do you export current flow data?


Use the React Flow instance and serialize it: call toObject() and then [Link](...) to
get a portable string you can download or send to a server.

Q272. What format is flow data usually saved in?


JSON. It’s easy to store, send, and restore ({ nodes, edges, viewport }).

Q273. How do you use toObject() to save flow state?


Get the instance with useReactFlow() (or from onInit), then:

const snap = [Link](); // { nodes, edges, viewport }

const json = [Link](snap);

Save json wherever you want.

Q274. How do you restore a saved flow?


Parse the JSON and set state:

const data = [Link](json);

setNodes([Link] || []);

setEdges([Link] || []);

[Link]([Link] || { x: 0, y: 0, zoom: 1 });

Optionally call fitView().

Q275. How do you persist flow in local storage?


On save, write to localStorage:

[Link]('flow', [Link]([Link]()));

Q276. How do you load flow from local storage?


Read the key, parse, and hydrate:
const raw = [Link]('flow');

if (raw) {

const data = [Link](raw);

setNodes([Link] || []);

setEdges([Link] || []);

[Link]([Link] || { x:0, y:0, zoom:1 });

Q277. Can you load flow from a database or API?


Yes. Fetch JSON from your API, then map it into nodes, edges, and viewport just like local
storage. Use stable IDs so updates remain consistent.

Q278. How do you trigger save after every change?


Listen to changes and debounce:

 Use onNodesChange, onEdgesChange, and onMoveEnd (viewport).

 In those handlers (or a useEffect watching nodes/edges/viewport), call [Link]()


and persist debounced to avoid spam.

Q279. What does onNodesChange return?


It receives an array of node change objects (e.g., position, add, remove, select). You pass
these to React Flow’s helpers (or the useNodesState handler) to update your state.

Q280. What does onEdgesChange return?


It receives an array of edge change objects (e.g., add, remove, select, update). You
forward these to your edges updater (or the useEdgesState handler) to keep state in
sync.

Q281. How do you merge restored data with existing flow?


Load the saved { nodes, edges }, then merge by ID: update existing items if IDs match,
add new ones if they don’t, and remove stale ones only if you intend to. After merging,
call setNodes, setEdges, and optionally fitView().

Q282. How do you clear saved flow?


Delete the stored snapshot and reset state. For localStorage:
[Link]('flow'); then setNodes([]), setEdges([]), and reset viewport with
setViewport({ x:0, y:0, zoom:1 }).

Q283. How do you store additional metadata with flow?


Extend the saved JSON:

{ nodes, edges, viewport, meta: { title, version, updatedAt, ownerId } }


Keep meta separate so you can evolve it without touching graph structure.

Q284. Can you auto-save flow every few seconds?


Yes. Use a setInterval or a debounced effect to call [Link]() and persist. Prefer
debounce on change (nodes/edges/viewport) to avoid saving when nothing changed.

Q285. How do you restore zoom position when loading flow?


Read viewport from the saved snapshot and call setViewport(viewport). If missing, use a
default { x:0, y:0, zoom:1 } or call fitView() after nodes/edges are set.

Q286. What is the best way to handle save/load errors?


Wrap JSON parse/stringify and storage calls in try/catch. Show a friendly message, log
details, and fall back to a safe default (empty graph). Validate the shape before
rendering.

Q287. Can multiple users work on the same flow simultaneously?


Yes, with real-time sync (WebSockets/WebRTC or services like Firebase/Supabase). You’ll
need conflict rules, server-side validation, and possibly operational transforms or last-
write-wins for edges/nodes.

Q288. How do you store flow history for undo/redo?


Keep a history stack of snapshots or patch operations. On each change, push a
compressed diff; on Undo, pop and restore; on Redo, reapply. Limit stack size to control
memory.

Q289. Can React Flow integrate with Firebase for persistence?


Absolutely. Save { nodes, edges, viewport, meta } to Firestore/RTDB, subscribe to
document changes, and update local state. Use security rules and validation on the
server side.

Q290. How do you validate loaded flow data before rendering?


Check the schema: arrays for nodes/edges, required fields (id, position for nodes; id,
source, target for edges), unique IDs, and matching source/target node IDs. If invalid,
reject and show an error or fallback graph.

10. Real-world Use Cases & Best Practices

Q291. How is React Flow used in workflow builders?


React Flow lets users drag steps (nodes), connect them (edges), and configure each step
in side panels. You get live validation (e.g., required inputs), versioned saves, and a clear
visual story of how data or tasks move through the system.
Q292. How is it used in automation tools like n8n or Zapier?
Each node represents an app action/trigger (Gmail → Slack, etc.). Edges define
execution order and data passing. Users can add, connect, and reorder nodes, then run
the flow and see statuses right on the canvas (success/error badges, timings).

Q293. How can React Flow help visualize AI pipelines?


Treat models, preprocessors, vector DB steps, and postprocessors as nodes. Edges show
data tensors/prompts moving between stages. You can display metrics (latency, tokens,
accuracy) on nodes/edges and let users A/B different branches.

Q294. How do you optimize React Flow for large graphs?


Use onlyRenderVisibleElements, memoize heavy components, keep
nodeTypes/edgeTypes and handlers in useMemo/useCallback, debounce onMove work,
lazy-load node content, and prefer lightweight DOM over complex nested trees.

Q295. How do you handle performance in big flows?


Use ID-stable updates (map by id), batch state with functional setNodes/setEdges, avoid
re-creating arrays/objects unnecessarily, throttle selection/hover effects, and offload
expensive layout to a Web Worker (e.g., Dagre/ELK run off-thread).

Q296. What is virtual rendering and does React Flow use it?
Virtual rendering means render only what the user sees. React Flow supports this via
onlyRenderVisibleElements, which skips offscreen nodes/edges to reduce DOM cost and
improve FPS on huge graphs.

Q297. How can you handle node overlap issues?


Run an auto-layout (Dagre/ELK) to space nodes, apply collision offsets in custom layout,
and allow users to fitView() or nudge nodes with keyboard. For parallel edges, use
smoothstep/step or a custom edge with slight path offsets.

Q298. What is the best way to manage React Flow state cleanly?
Use useNodesState/useEdgesState for minimal boilerplate, centralize actions (addNode,
removeNode, connect) and keep domain data separate from view state. Persist with
toObject() and restore on load; validate before rendering.

Q299. What are common mistakes beginners make with React Flow?

 No container height / missing [Link] → blank canvas

 Duplicate IDs for nodes/edges

 Heavy custom nodes without memoization

 Doing SSR rendering instead of client-only mount

 Not using onNodesChange/onEdgesChange, manually patching everything

 Forgetting fitView on first render for scattered graphs


Q300. What are some best practices for building production-ready flows?
Use unique, stable IDs, validate connections with isValidConnection, autosave with
debounce, keep UI snappy with onlyRenderVisibleElements, store snapshots via
toObject(), add undo/redo history, and protect with error boundaries + schema checks
before loading user data.

Q301. How do you allow only one parent node connection per node?
Validate incoming edges before creating a new one. In isValidConnection (on the target
handle), count edges with target === candidateTargetId. If ≥ 1, return false. Or in
onConnect, check and reject adding another incoming edge to that target.

Q302. How can you restrict each node to a maximum of 2 child connections?
On the source side, count edges where source === candidateSourceId. If the count is 2,
block the new connection via isValidConnection or skip adding it in onConnect.

Q303. How do you prevent circular connections (node connecting back to itself)?
Reject self-links with isValidConnection: ({ source, target }) => source !== target. For full
cycle prevention, run a quick graph check (DFS/BFS) to ensure the target isn’t an
ancestor of the source before accepting.

Q304. How can you disallow connections between certain node types (e.g., “Start”
cannot connect to “End”)?
Inside isValidConnection, read [Link] and [Link] (from your nodes
state or useReactFlow().getNode(id)) and return false for disallowed type pairs.

Q305. How do you validate connections dynamically based on custom business rules?
Use isValidConnection to inspect runtime data (node data, counts, user role, current
mode). You can also gate in onConnect for final checks before calling addEdge.

Q306. What is the use of the isValidConnection function in <Handle />?


It’s a per-handle predicate that decides if a dragged link can connect to this handle.
Returning true allows the drop; false blocks it—great for limits, type rules, and no-self
links.

Q307. How do you display an error message when an invalid connection is attempted?
In onConnect, run your validation. If it fails, don’t add the edge and show a
toast/snackbar (“Only one parent allowed”). Optionally, use onConnectEnd to detect
invalid drops (no edge created) and show a hint.

Q308. How can you highlight valid connection targets visually while dragging?
On onConnectStart, compute valid target handles and set a UI state (e.g., highlight=true
on those nodes/handles). Add a CSS class to glow them. Clear highlights on
onConnectEnd.

Q309. How can you disable connections temporarily during certain app states?
Set nodesConnectable={false} on <ReactFlow /> or pass isConnectable={false} to handles
based on app state (e.g., while running, in read-only mode).

Q310. How do you allow only one outgoing connection from a node?
Validate on the source: count edges where source === nodeId (or sourceHandle ===
handleId if per-handle). If ≥ 1, return false in isValidConnection or refuse in onConnect.

Q311. How do you allow only incoming connections on certain node types?
On those node types, render only target handles (no source handles). Additionally, set
isConnectable={false} on any accidental source handles. You can also guard in
isValidConnection to reject attempts where the source is that node type.

Q312. How do you remove existing edges when adding a new connection (to maintain
a single parent rule)?
In onConnect, before adding the new edge, filter out all edges with target ===
newTargetId, then append the incoming edge.

setEdges(es => addEdge(conn, [Link](e => [Link] === [Link] ? false : true)));

Q313. How can you check if a node already has a parent before allowing a new
connection?
Count incoming edges for the target:

const hasParent = getEdges().some(e => [Link] === targetId);

Use this inside isValidConnection or onConnect and block if hasParent is true.

Q314. How can you dynamically change handle connection rules based on node data?
Pass flags via [Link] (e.g., [Link], [Link]). In your <Handle />,
use isValidConnection={(c) => checkRules(c, data)}. Update data via setNodes to change
rules at runtime.

Q315. How can you programmatically reject a connection in onConnect handler?


Run your validations; if any fail, return early and don’t call addEdge. Optionally show a
toast/snackbar explaining why the connection was blocked.

Q316. How do you maintain a parent-child mapping in React Flow state?


Derive it from edges whenever they change, or keep a side map in state:

const parent = new Map(); const children = new Map();

[Link](e => { [Link]([Link], [Link]); ([Link]([Link]) ??=


[]).push([Link]); });
Recompute on onEdgesChange for a canonical tree-like view.

Q317. How can you limit connection depth (e.g., a node cannot go beyond 3 levels)?
Before accepting a new edge, compute the depth of the source by walking
[Link](node) upwards. If depth >= 3, reject in isValidConnection/onConnect.

Q318. How can you block connections between nodes that are already connected
indirectly?
Detect ancestor/descendant relationships to prevent creating an additional path (which
forms a DAG cross-link or cycle). Run a DFS/BFS from source to see if it already reaches
target (or vice versa). If found, reject.

Q319. How do you disable edge creation after a certain condition (e.g., task limit
reached)?
Flip a global flag (e.g., canConnect) and pass nodesConnectable={canConnect} to
<ReactFlow />. For finer control, set isConnectable={false} on specific handles while the
limit is active.

Q320. How can you enforce a tree structure connection logic using React Flow?
Combine rules: one parent per node, disallow cycles (ancestor check), optional max
children per node, and block cross-links between branches. Implement with
isValidConnection + guarded onConnect, and keep a parent/children map in sync with
edges to validate quickly.

Q321. How do you make nodes non-draggable based on their type or state?
Set draggable: false on those node objects, or compute it from [Link] when you
build nodes. Globally, you can keep nodesDraggable={true} but override per node: { ...n,
draggable: [Link] === 'locked' ? false : true }.

Q322. How do you restrict dragging within a specific area or grid?


Use nodeExtent={[[minX, minY], [maxX, maxY]]} to confine positions, and combine with
snapToGrid + snapGrid={[xStep, yStep]} so nodes land only on grid points.

Q323. How can you lock certain nodes so users can’t move or delete them?
Mark them with [Link] = true and set draggable:false. In your delete logic
(keyboard/Delete button), skip nodes with locked === true. Also hide handles or set
isConnectable={false} if they shouldn’t connect.

Q324. How do you snap nodes to a grid while dragging?


Enable on the canvas:

<ReactFlow snapToGrid snapGrid={[16, 16]} />

Now every drag drop aligns to 16×16 steps.

Q325. How can you create magnetic snapping to nearby nodes?


Listen to onNodeDrag/onNodeDragStop, detect nearby nodes (distance threshold), and
adjust the dragged node’s position to align edges/centers. For smoothness, show guide
lines and only snap when within a few pixels.

Q326. How do you make nodes resizable?


Wrap the node UI with a resizer (e.g., react-resizable or your own handles). On resize,
update width/height in data or style, then call updateNodeInternals(nodeId) so
edges/handles realign.

Q327. How do you show a context menu on right-click of a node?


Use onNodeContextMenu to prevent the default menu and open your own:

onNodeContextMenu={(e, node) => { [Link](); setMenu({ x:[Link],


y:[Link], node }); }}

Render a custom menu at those coordinates.

Q328. How do you handle Ctrl + Click or Shift + Click for multi-selection?
In onNodeClick, check modifier keys ([Link] / [Link]) and toggle the
selected flag for that node while preserving previous selections. Or rely on built-in multi-
select and just read it via onSelectionChange.

Q329. How do you dynamically change node color based on its connection state?
Compute style from edges: if a node has no incoming edge, make it warning color; if it
has errors, set red. Store a flag in data like [Link] and style:

<div className={[Link] ? 'border-green-500' : 'border-amber-500'} />

Q330. How can you disable specific handles dynamically based on node type?
Render <Handle /> with isConnectable={condition}. For example, in a “Sink” node:

<Handle type="target" position="left" isConnectable />

<Handle type="source" position="right" isConnectable={false} />

You can also hide the handle entirely based on [Link] or [Link].

Q331. How do you add tooltips or popovers to nodes on hover?


Use normal React tooltips inside your custom node. Quick way: add title={[Link]} to
an element. Rich way: show a tooltip/popover component (Radix, Headless UI, MUI) and
toggle it with onMouseEnter/onMouseLeave. Remember [Link]() on
interactive content so the canvas doesn’t drag.

Q332. How do you highlight connected edges when hovering a node?


In onNodeMouseEnter, collect edge IDs where [Link] === [Link] || [Link]
=== [Link] and set a UI flag (e.g., highlightedEdgeIds). Style those edges via style or a
class (thicker stroke, color). Clear the highlight in onNodeMouseLeave.
Q333. How can you implement node grouping (like folders or swimlanes)?
Use parent nodes. Create a big “group” node and set children with parentNode: 'group-
1' and extent: 'parent' so they stay inside. Style the group node like a lane/card and
render its title in a custom node component.

Q334. How can you collapse or expand node groups dynamically?


Track groupCollapsed in the group node’s data. When collapsing, hide children (filter
them from nodes or set hidden: true) and optionally resize the group node. On expand,
restore the children and call fitView() or updateNodeInternals(groupId).

Q335. How do you make a node display live data from an API?
Fetch externally (React Query/SWR/useEffect), store results in app state, then pass into
the node via data. Update the node with setNodes when data changes so the node re-
renders. Show loading/error states inside the node UI.

Q336. How can you use React Flow with drag-and-drop node creation (from a sidebar)?
Use HTML5 DnD. On the pane, implement onDrop and onDragOver. Convert screen
coords to flow coords with useReactFlow().project({ x, y }), then setNodes(ns => [...ns,
newNodeAtProjectedPos]).

Q337. How can you delete nodes by pressing the Delete or Backspace key?
Listen for keydown on your app. When Delete/Backspace, read getNodes().filter(n =>
[Link]) and call deleteElements({ nodes: selected }) or setNodes/setEdges to remove
them. Also handle onNodesDelete for cleanup.

Q338. How do you auto-align nodes in a structured layout after creation?


Run an auto-layout (Dagre or ELK). Compute new { x, y } for each node, then
setNodes(mapWithNewPositions) and fitView(). Do this after batch additions or on a
“Auto-Layout” button.

Q339. How do you show selection rectangles to select multiple nodes?


React Flow supports box selection out of the box (drag on empty pane). If needed,
enable/tune with props like selectionOnDrag. Use onSelectionChange to react to the
current selection.

Q340. How can you automatically reposition child nodes when a parent moves?
Use nested nodes: set children’s parentNode to the parent ID. They’ll move with the
parent automatically. Add extent: 'parent' to keep them inside; call
updateNodeInternals(parentId) after size changes so handles/edges realign.

Q341. How do you create a custom edge type?


Write a React component that returns an SVG path and register it in edgeTypes. Then set
type on your edge.

const edgeTypes = { fancy: FancyEdge };


<ReactFlow edges={edges} edgeTypes={edgeTypes} />

// edge: { id:'e1-2', source:'1', target:'2', type:'fancy' }

Q342. How do you render custom edge paths using SVG curves?
In your edge component, compute an SVG d path (use helpers like getBezierPath /
getSmoothStepPath or your own math) and render <path d={edgePath} />.

const [edgePath] = getBezierPath({ sourceX, sourceY, targetX, targetY });

return <path d={edgePath} className="react-flow__edge-path" />;

Q343. How can you add arrow markers or icons on custom edges?
Define an SVG <marker> inside <defs> and reference it via markerEnd (or markerStart).

<defs>

<marker id="arrow" markerWidth="10" markerHeight="10" refX="10" refY="5"


orient="auto">

<path d="M0,0 L10,5 L0,10 z" />

</marker>

</defs>

<path d={edgePath} markerEnd="url(#arrow)" />

Q344. How do you handle click events on custom edges?


Attach handlers to the rendered path (or wrapper <g>). React Flow will pass data via
props.

<path d={edgePath} onClick={(e) => onSelectEdge(id)} className="react-flow__edge-


path" />

Q345. How can you color edges based on connection validity?


Set stroke conditionally (from edge data or validation state).

<path d={edgePath} style={{ stroke: isValid ? '#16a34a' : '#ef4444' }} />

You can also use classes for success/error themes.

Q346. How can you dynamically update edge style when nodes move?
Custom edges receive live sourceX/Y and targetX/Y. Recompute the path on each render;
React Flow re-renders when nodes move, so your edge redraws automatically. For heavy
math, memoize.

Q347. How do you create bidirectional edges?


Use two edges between the same pair with opposite directions, each with its own
markerEnd. Slightly offset paths to avoid overlap (e.g., add a small curve offset or custom
control points).

Q348. How can you add animated edges with pulse effects?
Use CSS animation on the path’s stroke or dash.

<path d={edgePath} style={{ strokeDasharray: '6 4' }} className="pulsing-edge" />

/* CSS */

.pulsing-edge { animation: dash 1.2s linear infinite; }

@keyframes dash { to { stroke-dashoffset: -20; } }

Q349. How do you show edge labels only on hover?


Render the label with EdgeLabelRenderer, and toggle visibility with hover state
(onMouseEnter/Leave).

{hovered && (

<EdgeLabelRenderer>

<div style={{ transform: `translate(-50%, -50%) translate(${labelX}px, ${labelY}px)` }}>

{label}

</div>

</EdgeLabelRenderer>

)}

Q350. How can you display data (like a percentage) on edge labels?
Store the value in [Link] (e.g., data: { pct: 73 }) and render it in your custom
edge/label:

<EdgeLabelRenderer>

<div style={{ transform: `translate(-50%, -50%) translate(${x}px, ${y}px)` }}>

{[Link]}%

</div>

</EdgeLabelRenderer>

Update [Link] in state to keep the label live.

Q351. How can you prevent overlapping edges visually?


Use edge types that route cleanly (smoothstep or step) and add slight offsets for parallel
edges via a custom edge (small perpendicular shift). Reduce crossings with auto-layout
(Dagre/ELK) and widen hit/label areas so paths don’t visually collide.
Q352. How do you update an edge’s label when node data changes?
When node data changes (e.g., in onNodesChange or your own setter), recompute the
label and update the matching edge:

setEdges(es => [Link](e => [Link] === edgeId ? { ...e, label: computeLabelFrom(nodes) } :
e));

If the label derives from [Link], update that and render [Link].

Q353. How can you highlight all edges connected to a selected node?
On onSelectionChange, get the selected node IDs, then style edges whose source or
target matches:

setEdges(es => [Link](e => ([Link]([Link]) || [Link]([Link]))

? { ...e, style:{ ...[Link], strokeWidth: 3 } }

: { ...e, style:{ ...[Link], strokeWidth: 1 } }));

Q354. How do you conditionally render different edge components?


Register multiple edgeTypes and switch the type field per edge (or swap it dynamically
based on [Link]):

const edgeTypes = { ok: OkEdge, warn: WarnEdge };

setEdges(es => [Link](e => ({ ...e, type: [Link] > 0 ? 'warn' : 'ok' })));

Q355. How do you delete an edge by right-click or button click?


Use onEdgeContextMenu or onEdgeClick and then filter it out:

const removeEdge = (id) => setEdges(es => [Link](e => [Link] !== id));

Show a confirm menu or inline “Delete” button in a custom edge/label.

Q356. How do you use updateEdge() to programmatically change edge properties?


Use it to reconnect an edge’s endpoints:

import { updateEdge } from 'reactflow';

setEdges(es => {

const edge = [Link](e => [Link] === id);

return updateEdge(edge, { source, sourceHandle, target, targetHandle }, es);

});

For styling/labels, just map and mutate the edge object with setEdges.

Q357. How can you animate edge creation smoothly (like drawing a wire)?
Add the edge with a dashed stroke and CSS animation (dash offset) for a second, then
switch to solid: create edge → apply .animated class → setTimeout to remove the class
or set animated: true initially and disable after completion.

Q358. How do you detect edge direction (source → target) and act on it?
Edges are directional via source and target. In onConnect/onEdgesChange, inspect them
to run business logic (e.g., block reverse links, compute topological order, or set different
markers per direction).

Q359. How can you group multiple edges visually between the same nodes?
Either (a) draw slightly offset parallel paths for each edge (custom edge with index-
based offset), or (b) bundle: render a single path and a badge showing the count (e.g.,
“×3”) using EdgeLabelRenderer.

Q360. How do you create loop edges (node connects to itself visually)?
Use a custom edge that, when source === target, draws a small curved loop anchored to
the node’s bounds (e.g., a cubic Bézier with control points offset above/right). Place the
label along the loop with EdgeLabelRenderer.

Q361. How do you use useReactFlow() to control zoom and fit programmatically?
Call the hook to get helpers and then invoke them on events/buttons:
const { fitView, zoomIn, zoomOut, zoomTo, setViewport } = useReactFlow();
Use zoomIn()/zoomOut() for relative zoom, zoomTo(1.2) for an exact level, fitView({
padding: 0.2 }) to frame everything, or setViewport({ x, y, zoom }) for full control.

Q362. How do you get the current viewport position using React Flow instance?
Use const { getViewport } = useReactFlow(); then const vp = getViewport();.
It returns { x, y, zoom } describing current pan and zoom; great for saving/restoring
camera.

Q363. How do you find and update a node by ID in the current flow?
Read with getNode(id) from useReactFlow(). Update via state:

setNodes(ns => [Link](n => [Link] === id ? { ...n, data: { ...[Link], label: 'Updated' } } : n));

If size/handles change, call updateNodeInternals(id).

Q364. How do you add new nodes dynamically on user actions?


On click/drop, project screen coords and append:

const { project } = useReactFlow();

const pos = project({ x: clientX, y: clientY });

setNodes(ns => [...ns, { id, position: pos, data: { label }, type: 'default' }]);

Q365. How can you track all connection changes globally?


Wire these on <ReactFlow />: onConnect (new edge), onEdgeUpdateStart/End,
onEdgeUpdate, and onEdgesChange. Centralize them to log, validate, and persist.
Q366. How do you save flow data to a backend API in real time?
Debounce a saver that posts useReactFlow().toObject() whenever onNodesChange,
onEdgesChange, or onMoveEnd fires. Handle errors with retries/backoff, and show a
small “Saving…”/“Saved” status.

Q367. How can you restore flow from JSON data programmatically?
Parse JSON, set state, then restore camera:

const data = [Link](json);

setNodes([Link] || []);

setEdges([Link] || []);

setViewport([Link] || { x:0, y:0, zoom:1 });

Optionally call fitView() after nodes/edges mount.

Q368. How do you merge partial updates into the existing flow?
Map by ID and shallow-merge fields:

setNodes(ns => [Link](n => patch[[Link]] ? { ...n, ...patch[[Link]] } : n));

setEdges(es => [Link](e => patchE[[Link]] ? { ...e, ...patchE[[Link]] } : e));

Add missing items, skip unknowns; keep IDs stable.

Q369. How can you implement undo/redo feature in React Flow?


Maintain two stacks: past and future. On every confirmed change, push a snapshot
(toObject() or diffs) to past.

 Undo: pop from past, push current to future, restore popped snapshot.

 Redo: reverse the process.


Limit stack size and debounce snapshotting.

Q370. How can you track and log user interactions on nodes and edges?
Attach handlers: onNodeClick, onEdgeClick, onNodeDragStart/Stop, onConnect,
onSelectionChange, onMoveEnd. In each, capture metadata (IDs, timestamps, viewport)
and send to analytics or your logger.

Q371. How do you auto-save flow state after every change?


Listen to onNodesChange, onEdgesChange, and onMoveEnd. Debounce a saver that calls
toObject() and writes to localStorage or your API. This avoids saving too often while still
capturing every edit.

Q372. How do you sync flow state with an external store (like Zustand or Redux)?
Keep nodes, edges, and viewport in the store. Pass store values into <ReactFlow />, and
forward onNodesChange/onEdgesChange to dispatch/setters. Use selectors to read state
and keep actions like addNode, removeEdge centralized.

Q373. How can you undo accidental deletions using keyboard shortcuts?
Maintain an undo/redo stack of snapshots (or diffs). On keydown for Ctrl+Z / Cmd+Z,
restore the previous snapshot; for Shift+Ctrl+Z, redo. Push snapshots after confirmed
changes (with debounce to limit noise).

Q374. How do you preserve viewport state when reloading the page?
Save { x, y, zoom } from getViewport() on onMoveEnd. On load, read it and call
setViewport(savedViewport) after setting nodes/edges. Fallback to fitView() if nothing
was saved.

Q375. How can you filter visible nodes based on search input dynamically?
Compute a filtered list from the search text. Either (a) set hidden: true for unmatched
nodes and their edges, or (b) render only the filtered subsets. Optionally auto-zoom with
fitView() after filtering.

Q376. How do you optimize React Flow for large graphs (1000+ nodes)?
Enable onlyRenderVisibleElements, memoize node/edge components, keep handlers
stable with useCallback, avoid recreating arrays/objects, run layout in a Web Worker,
and simplify node DOM (fewer nested components).

Q377. What is node virtualization, and does React Flow support it?
Virtualization means render only what’s on screen. Yes—use onlyRenderVisibleElements
so offscreen nodes/edges don’t mount, cutting DOM size and boosting FPS.

Q378. How can you reduce re-renders in large node networks?


Use functional updates (setNodes(ns => ...)), keep nodeTypes/edgeTypes in useMemo,
memoize custom nodes with [Link], keep props shallow and stable, and avoid
storing volatile UI flags in every node object.

Q379. How do you use memo or useMemo with custom nodes for optimization?
Wrap the node component with [Link] and only pass minimal props (e.g., data,
selected). Use useMemo for heavy calculations inside the node so they recompute only
when inputs change.

Q380. How can you lazy-load parts of a large flow diagram?


Split the graph into regions or pages. Load nodes/edges for the current region based on
zoom/viewport or user navigation. For remote data, fetch on demand; for local data,
chunk and append as the camera moves, then call fitView() when needed.

Q381. How do you handle performance bottlenecks in frequent state updates?


Use functional updates (setNodes(ns => ...), setEdges(es => ...)), memoize handlers with
useCallback, memoize heavy maps with useMemo, and avoid recreating arrays/objects
unnecessarily. Push transient UI flags (hover, temp highlights) into local component
state, not every node object.

Q382. How do you batch updates to reduce render frequency?


Combine related changes into a single setNodes / setEdges call. When multiple updates
are required, wrap them in one function update so React batches them naturally:

setNodes(ns => [Link](/* all edits here at once */));

setEdges(es => [Link](/* all edits here at once */));

Debounce high-frequency handlers (onMove, onMouseMove).

Q383. How can you avoid layout shifts while nodes load async data?
Reserve space with a fixed min width/height or skeleton UI in the node. When data
arrives, replace content but keep size stable. If size must change, call
updateNodeInternals(id) after update to realign edges smoothly.

Q384. How do you disable animations for large-scale flows?


Skip animated edges (animated: false), remove CSS transitions, and avoid expensive
hover effects. Turn off shadows/filters, prefer solid colors, and disable non-essential
features like edge dash animations.

Q385. How can you implement virtual scrolling or pagination in flows?


Use onlyRenderVisibleElements to virtualize by viewport. For very large graphs,
paginate: render one region/page at a time based on zoom or navigation, and
fetch/append nodes for the active window only.

Q386. How do you export flow as an image or PDF?


Use a DOM-to-image or canvas capture (e.g., html-to-image, dom-to-image-more) on the
ReactFlow wrapper to get PNG/JPEG. For PDF, pipe the image into a client-side PDF
library (e.g., jspdf). Fit the viewport first with fitView() for a clean frame.

Q387. How do you export flow as JSON for external tools?


Serialize with:

const json = [Link](useReactFlow().toObject()); // { nodes, edges, viewport }

Download it or POST to your API. Keep IDs stable so other tools can map references.

Q388. How do you import flow from external JSON or API?


Fetch/parse JSON, validate shape, then:

setNodes([Link] || []);

setEdges([Link] || []);

setViewport([Link] || { x:0, y:0, zoom:1 });


Run fitView() if no viewport is included.

Q389. How can you auto-layout nodes using libraries like Dagre or ELK?
Build a graph from your nodes/edges, run Dagre/ELK to compute positions, then write
back:

const laidOut = layout(nodes, edges); // your Dagre/ELK wrapper

setNodes([Link]);

setEdges([Link]);

fitView();

Do heavy layout in a Web Worker to keep the UI responsive.

Q390. How can you highlight a specific path programmatically?


Given a list of node IDs (or edges) on the path, map edges and set a highlight style:

setEdges(es => [Link](e => [Link]([Link])

? { ...e, style:{ ...[Link], strokeWidth:3 }, animated:true }

: { ...e, style:{ ...[Link], strokeWidth:1 }, animated:false }));

Also highlight the path’s nodes for clarity and call fitView({ nodes: targetNodes }) to
focus the camera.

Q391. How can you implement keyboard shortcuts for zoom, undo, etc.?
Add a keydown listener on your app (or use a hotkeys lib). Call useReactFlow() methods:
zoomIn(), zoomOut(), fitView(). Maintain an undo/redo stack and handle Ctrl/Cmd+Z /
Shift+Ctrl/Cmd+Z to restore snapshots. Prevent default where needed (e.g., browser
zoom).

Q392. How do you change cursor styles during drag operations?


Toggle a CSS class on drag start/stop (onNodeDragStart / onNodeDragStop) and style it:
.dragging { cursor: grabbing; }. You can also target Flow classes like .react-flow__pane
and .react-flow__node.dragging.

Q393. How do you display edge creation hints when connecting?


Use onConnectStart to compute valid targets and set a “hint” state. Visually glow valid
handles/nodes (CSS class). Optionally show a tooltip near the cursor with guidance
(“Connect to a target handle”).

Q394. How do you show connection preview lines before dropping?


Use the built-in preview via connection line props: connectionLineStyle or a custom
connectionLineComponent on <ReactFlow />. This renders a live wire from the source
handle to the cursor.
Q395. How can you integrate minimap synchronization with selected nodes?
In <MiniMap />, set nodeColor={(n) => ([Link] ? '#6366f1' : '#94a3b8')} and maybe
maskColor for the viewport. Update automatically via onSelectionChange—selection
state already flows into the MiniMap.

Q396. How can you customize control buttons (zoom, fit, lock)?
Use <Controls /> with flags like showZoom, showFitView, showInteractive. Add custom
actions via <ControlButton> children (your own icons, tooltips). Position with
position="top-left" etc.; style via class overrides.

Q397. How do you auto-fit view after adding or removing nodes dynamically?
Call fitView({ padding: 0.2 }) after node/edge mutations. Common pattern: a debounced
useEffect on [Link]/[Link] or handle inside
onNodesChange/onEdgesChange after “add/remove” changes.

Q398. How can you connect React Flow with external logic engines (e.g., workflow
execution)?
Map the graph (nodes, edges) to your engine’s DAG schema. Validate with
isValidConnection, then on “Run” send JSON to the backend/executor. Stream live status
back per node (running/success/error) and update [Link] to reflect execution.

Q399. How do you implement real-time collaboration (multi-user flow editing)?


Use WebSockets/CRDTs (e.g., [Link]). Broadcast intent-level ops (addNode, moveNode,
addEdge) instead of whole snapshots. Show presence (cursors/colors), lock elements
being edited, resolve conflicts with last-write-wins or OT/CRDT merge.

Q400. How do you integrate React Flow with WebSockets for live flow updates?
Create channels like nodes:update, edges:update, viewport:update. On receive, apply
updates with setNodes/setEdges (ID-stable patches). Debounce sends on local changes,
use optimistic UI, and reconcile server echoes to keep all clients in sync.

You might also like