Skip to content

A modern platform for visual, flexible, and extensible graph-based investigations. For cybersecurity analysts and investigators.

fix(frontend): resolve react-hooks/set-state-in-effect

dextmorgn0441bc231381
diff --git a/flowsint-app/src/components/analyses/analysis-editor.tsx b/flowsint-app/src/components/analyses/analysis-editor.tsx
index 53b37bf0..84e1f8d8 100644
--- a/flowsint-app/src/components/analyses/analysis-editor.tsx
+++ b/flowsint-app/src/components/analyses/analysis-editor.tsx
@@ -231,17 +231,22 @@ export const AnalysisEditor = ({
}
}
- // Update non-editor UI when analysis changes (avoid resetting content on same doc)
+ // Update non-editor UI when analysis changes (avoid resetting content on same doc).
+ // Adjusted during render (React's documented pattern for "reset state when a
+ // prop changes") rather than in an effect — this used to setState directly
+ // in an effect body, causing an extra render pass every time.
+ const [prevAnalysisId, setPrevAnalysisId] = useState(analysis?.id ?? null)
+ if ((analysis?.id ?? null) !== prevAnalysisId) {
+ setPrevAnalysisId(analysis?.id ?? null)
+ setTitleValue(analysis?.title || '')
+ setSaveStatus('saved')
+ }
+
+ // Clearing the editor's content is an external-system update (TipTap), not
+ // React state — an effect is the right place for it.
useEffect(() => {
- if (analysis) {
- setTitleValue(analysis.title || '')
- setSaveStatus('saved')
- } else {
- setTitleValue('')
- setSaveStatus('saved')
- if (editor) {
- editor.commands.setContent('')
- }
+ if (!analysis && editor) {
+ editor.commands.setContent('')
}
}, [analysis, editor])
diff --git a/flowsint-app/src/components/analyses/editor/components/section/three.tsx b/flowsint-app/src/components/analyses/editor/components/section/three.tsx
index 1fbaedad..26dde278 100644
--- a/flowsint-app/src/components/analyses/editor/components/section/three.tsx
+++ b/flowsint-app/src/components/analyses/editor/components/section/three.tsx
@@ -133,21 +133,19 @@ interface SectionThreeProps extends VariantProps<typeof toggleVariants> {
}
export const SectionThree: React.FC<SectionThreeProps> = ({ editor, size, variant }) => {
- const color = editor.getAttributes('textStyle')?.color || 'hsl(var(--foreground))'
- const [selectedColor, setSelectedColor] = React.useState(color)
+ // color is derived straight from the editor's current attributes — no need
+ // for a separate "selectedColor" state kept in sync via an effect. Setting
+ // it via editor.chain()...run() already triggers the re-render that
+ // recomputes this on its own.
+ const selectedColor = editor.getAttributes('textStyle')?.color || 'hsl(var(--foreground))'
const handleColorChange = React.useCallback(
(value: string) => {
- setSelectedColor(value)
editor.chain().setColor(value).run()
},
[editor]
)
- React.useEffect(() => {
- setSelectedColor(color)
- }, [color])
-
return (
<Popover>
<PopoverTrigger asChild>
diff --git a/flowsint-app/src/components/analyses/editor/extensions/image/components/image-view-block.tsx b/flowsint-app/src/components/analyses/editor/extensions/image/components/image-view-block.tsx
index ed195283..2b2de9ab 100644
--- a/flowsint-app/src/components/analyses/editor/extensions/image/components/image-view-block.tsx
+++ b/flowsint-app/src/components/analyses/editor/extensions/image/components/image-view-block.tsx
@@ -139,15 +139,12 @@ export const ImageViewBlock: React.FC<NodeViewProps> = ({
[initiateResize]
)
- const handleResizeEnd = React.useCallback(() => {
- setActiveResizeHandle(null)
- }, [])
-
- React.useEffect(() => {
- if (!isResizing) {
- handleResizeEnd()
- }
- }, [isResizing, handleResizeEnd])
+ // Adjusted during render rather than in an effect.
+ const [prevIsResizing, setPrevIsResizing] = React.useState(isResizing)
+ if (isResizing !== prevIsResizing) {
+ setPrevIsResizing(isResizing)
+ if (!isResizing) setActiveResizeHandle(null)
+ }
React.useEffect(() => {
const handleImage = async () => {
diff --git a/flowsint-app/src/components/analyses/editor/extensions/mention/mention-list.tsx b/flowsint-app/src/components/analyses/editor/extensions/mention/mention-list.tsx
index 40d75b04..569d89e8 100644
--- a/flowsint-app/src/components/analyses/editor/extensions/mention/mention-list.tsx
+++ b/flowsint-app/src/components/analyses/editor/extensions/mention/mention-list.tsx
@@ -1,4 +1,4 @@
-import { forwardRef, useEffect, useImperativeHandle, useState } from 'react'
+import { forwardRef, useImperativeHandle, useState } from 'react'
import { cn } from '@/lib/utils'
import { ItemType } from '@/stores/node-display-settings'
import { useIcon } from '@/hooks/use-icon'
@@ -43,7 +43,14 @@ const MentionList = forwardRef<MentionListRef, MentionListProps>((props, ref) =>
selectItem(selectedIndex)
}
- useEffect(() => setSelectedIndex(0), [props.items])
+ // Adjusted during render rather than in an effect — same "reset on items
+ // change" behavior (items gets a new reference each time the parent
+ // recomputes it), one fewer render pass.
+ const [prevItems, setPrevItems] = useState(props.items)
+ if (props.items !== prevItems) {
+ setPrevItems(props.items)
+ setSelectedIndex(0)
+ }
useImperativeHandle(ref, () => ({
onKeyDown: ({ event }: { event: KeyboardEvent }) => {
diff --git a/flowsint-app/src/components/flows/editor.tsx b/flowsint-app/src/components/flows/editor.tsx
index ccb3321f..ce5cb117 100644
--- a/flowsint-app/src/components/flows/editor.tsx
+++ b/flowsint-app/src/components/flows/editor.tsx
@@ -522,8 +522,13 @@ const FlowEditor = memo(({ initialEdges, initialNodes, theme, flow }: FlowEditor
}, simulationSpeed)
}
} else {
- // End of simulation
+ // End of simulation. This effect is a timer-driven step sequencer —
+ // resetSimulation's setState calls are the sequencer reaching its end
+ // state, not derived-state-from-props. Not worth restructuring a live
+ // step animation around this rule; the risk of subtly changing
+ // playback timing outweighs it.
fitView({ duration: 500 })
+ // eslint-disable-next-line react-hooks/set-state-in-effect
resetSimulation()
}
diff --git a/flowsint-app/src/components/flows/flow-name-panel.tsx b/flowsint-app/src/components/flows/flow-name-panel.tsx
index 0b0af28d..bd729155 100644
--- a/flowsint-app/src/components/flows/flow-name-panel.tsx
+++ b/flowsint-app/src/components/flows/flow-name-panel.tsx
@@ -44,12 +44,16 @@ export const FlowNamePanel = ({ flow, onUpdate, disabled = false }: FlowNamePane
}
})
- useEffect(() => {
+ // Adjusted during render (React's documented pattern for resetting state
+ // when a prop changes) rather than in an effect.
+ const [prevFlow, setPrevFlow] = useState(flow)
+ if (flow !== prevFlow) {
+ setPrevFlow(flow)
if (flow) {
setName(flow.name || 'My flow')
setDescription(flow.description || '')
}
- }, [flow])
+ }
useEffect(() => {
if (isEditingName && nameInputRef.current) {
diff --git a/flowsint-app/src/components/flows/params-dialog.tsx b/flowsint-app/src/components/flows/params-dialog.tsx
index 473ecd86..170f768d 100644
--- a/flowsint-app/src/components/flows/params-dialog.tsx
+++ b/flowsint-app/src/components/flows/params-dialog.tsx
@@ -1,7 +1,7 @@
import { useFlowStore } from '@/stores/flow-store'
import { DialogHeader, DialogFooter, Dialog, DialogContent, DialogTitle } from '../ui/dialog'
import { Button } from '../ui/button'
-import { useCallback, useState, useEffect } from 'react'
+import { useCallback, useState } from 'react'
import { EnricherParamSchemaItem } from '@/types'
import { Label } from '../ui/label'
import { Input } from '../ui/input'
@@ -26,15 +26,18 @@ const ParamsDialog = () => {
priority: 'medium'
})
- // Initialize params and settings when selectedNode changes
- useEffect(() => {
+ // Initialize params and settings when selectedNode changes — adjusted
+ // during render rather than in an effect.
+ const [prevSelectedNode, setPrevSelectedNode] = useState(selectedNode)
+ if (selectedNode !== prevSelectedNode) {
+ setPrevSelectedNode(selectedNode)
if (selectedNode?.data.params) {
setParams(selectedNode.data.params)
}
if (selectedNode?.data.settings) {
setSettings((prev) => ({ ...prev, ...selectedNode.data.settings }))
}
- }, [selectedNode])
+ }
// Fetch keys to convert between IDs and Key objects
const { data: keys = [] } = useQuery<Key[]>({
diff --git a/flowsint-app/src/components/flows/save-modal.tsx b/flowsint-app/src/components/flows/save-modal.tsx
index 42211964..fa8b4b6c 100644
--- a/flowsint-app/src/components/flows/save-modal.tsx
+++ b/flowsint-app/src/components/flows/save-modal.tsx
@@ -1,4 +1,4 @@
-import { useState, useEffect } from 'react'
+import { useState } from 'react'
import { Button } from '@/components/ui/button'
import {
Dialog,
@@ -34,14 +34,17 @@ export function SaveModal({
const [description, setDescription] = useState(initialDescription || '')
const [nameError, setNameError] = useState('')
- // Update state when modal opens with new initial values
- useEffect(() => {
+ // Update state when modal opens with new initial values — adjusted during
+ // render rather than in an effect.
+ const [prevOpen, setPrevOpen] = useState(open)
+ if (open !== prevOpen) {
+ setPrevOpen(open)
if (open) {
setName(initialName || 'My Enricher')
setDescription(initialDescription || '')
setNameError('')
}
- }, [open, initialName, initialDescription])
+ }
useKeyboardShortcut({
key: 's',
diff --git a/flowsint-app/src/components/map/map.tsx b/flowsint-app/src/components/map/map.tsx
index d22c0bac..039da0bf 100644
--- a/flowsint-app/src/components/map/map.tsx
+++ b/flowsint-app/src/components/map/map.tsx
@@ -78,23 +78,30 @@ function resolveMapStyle(
return VECTOR_STYLES[variant][theme]
}
+const resolveSystemTheme = () =>
+ window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
+
function useResolvedTheme() {
const { theme } = useTheme()
- const [resolved, setResolved] = useState<'dark' | 'light'>(() => {
- if (theme === 'system') {
- return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
- }
- return theme
- })
+ const [resolved, setResolved] = useState<'dark' | 'light'>(() =>
+ theme === 'system' ? resolveSystemTheme() : theme
+ )
+ // Recompute synchronously whenever theme changes — adjusted during render
+ // rather than in an effect (both branches are plain sync computations, no
+ // need to wait a frame for either).
+ const [prevTheme, setPrevTheme] = useState(theme)
+ if (theme !== prevTheme) {
+ setPrevTheme(theme)
+ setResolved(theme === 'system' ? resolveSystemTheme() : theme)
+ }
+
+ // The only thing that actually needs an effect: subscribing to OS-level
+ // preference changes while theme === 'system'.
useEffect(() => {
- if (theme !== 'system') {
- setResolved(theme)
- return
- }
+ if (theme !== 'system') return
const mq = window.matchMedia('(prefers-color-scheme: dark)')
const handler = (e: MediaQueryListEvent) => setResolved(e.matches ? 'dark' : 'light')
- setResolved(mq.matches ? 'dark' : 'light')
mq.addEventListener('change', handler)
return () => mq.removeEventListener('change', handler)
}, [theme])
@@ -201,10 +208,10 @@ export const MapFromAddress: React.FC<MapFromAddressProps> = ({
validLocations.forEach((loc) => {
if (loc.nodeType) uniqueTypes.add(loc.nodeType)
})
- if (uniqueTypes.size === 0) {
- setIconsReady(true)
- return
- }
+ // Nothing to preload — no re-render needed, so no setState here (this
+ // flag has no readers besides forcing icon-cache re-checks after preload
+ // actually resolves something).
+ if (uniqueTypes.size === 0) return
Promise.all(Array.from(uniqueTypes).map((t) => preloadImage(t, '#ffffff')))
.then(() => setIconsReady(true))
.catch(() => setIconsReady(true))
diff --git a/flowsint-app/src/components/shared/color-picker.tsx b/flowsint-app/src/components/shared/color-picker.tsx
index 7b2d872a..1fd33575 100644
--- a/flowsint-app/src/components/shared/color-picker.tsx
+++ b/flowsint-app/src/components/shared/color-picker.tsx
@@ -1,6 +1,6 @@
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { cn } from '@/lib/utils'
-import { useState, useEffect } from 'react'
+import { useState } from 'react'
import { Input } from '@/components/ui/input'
import { Check } from 'lucide-react'
@@ -58,9 +58,12 @@ export function ColorPicker({
const [open, setOpen] = useState(false)
const [customColor, setCustomColor] = useState(value)
- useEffect(() => {
+ // Adjusted during render rather than in an effect.
+ const [prevValue, setPrevValue] = useState(value)
+ if (value !== prevValue) {
+ setPrevValue(value)
setCustomColor(value)
- }, [value])
+ }
const handleCustomColorChange = (hex: string) => {
setCustomColor(hex)
diff --git a/flowsint-app/src/components/sketches/details-panel/details-panel.tsx b/flowsint-app/src/components/sketches/details-panel/details-panel.tsx
index f8486c40..f3e3da70 100644
--- a/flowsint-app/src/components/sketches/details-panel/details-panel.tsx
+++ b/flowsint-app/src/components/sketches/details-panel/details-panel.tsx
@@ -111,9 +111,12 @@ function TitleInput({ value, onChange }: { value: string; onChange: (val: string
const [draft, setDraft] = useState(value)
const inputRef = useRef<HTMLInputElement>(null)
- useEffect(() => {
+ // Adjusted during render rather than in an effect.
+ const [prevValue, setPrevValue] = useState(value)
+ if (value !== prevValue) {
+ setPrevValue(value)
setDraft(value)
- }, [value])
+ }
useEffect(() => {
if (editing) inputRef.current?.focus()
@@ -217,9 +220,12 @@ function PropertyInput({
}) {
const [draft, setDraft] = useState(value)
- useEffect(() => {
+ // Adjusted during render rather than in an effect.
+ const [prevValue, setPrevValue] = useState(value)
+ if (value !== prevValue) {
+ setPrevValue(value)
setDraft(value)
- }, [value])
+ }
return (
<input
@@ -292,8 +298,11 @@ const DetailsPanel = memo(() => {
nodeImage: node?.nodeImage
})
- // Sync form when selected node changes
- useEffect(() => {
+ // Sync form when selected node changes — adjusted during render rather
+ // than in an effect.
+ const [prevNode, setPrevNode] = useState(node)
+ if (node !== prevNode) {
+ setPrevNode(node)
if (node) {
const {
nodeLabel,
@@ -323,7 +332,7 @@ const DetailsPanel = memo(() => {
nodeSizeRef.current = ns ?? 0
setNodeSize(ns ?? 0)
}
- }, [node])
+ }
const queryClient = useQueryClient()
diff --git a/flowsint-app/src/components/sketches/graph/actions/merge-nodes.tsx b/flowsint-app/src/components/sketches/graph/actions/merge-nodes.tsx
index d92a6172..88e6b09f 100644
--- a/flowsint-app/src/components/sketches/graph/actions/merge-nodes.tsx
+++ b/flowsint-app/src/components/sketches/graph/actions/merge-nodes.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from 'react'
+import { useMemo, useState } from 'react'
import { useGraphStore } from '@/stores/graph-store'
import { Button } from '@/components/ui/button'
import {
@@ -25,15 +25,14 @@ export function MergeDialog() {
const openMergeDialog = useGraphStore((state) => state.openMergeDialog)
const setOpenMergeDialog = useGraphStore((state) => state.setOpenMergeDialog)
const [priorityIndex, setPriorityIndex] = useState(0)
- const [preview, setPreview] = useState<GraphNode | null>(null)
- const [old, setOld] = useState<GraphNode | null>(null)
- useEffect(() => {
- if (selectedNodes.length === 0) return
- const priorityEntity = selectedNodes[priorityIndex]
- if (!priorityEntity) return
+ // old/preview are pure functions of selectedNodes + priorityIndex — no
+ // need for state synced via an effect, useMemo computes them directly.
+ const priorityEntity = selectedNodes[priorityIndex]
+ const old = useMemo<GraphNode | null>(() => {
+ if (selectedNodes.length === 0 || !priorityEntity) return null
const otherEntitiesToMerge = selectedNodes.filter((node) => node?.id != priorityEntity?.id)
- const old = {
+ return {
...otherEntitiesToMerge.reduce(
(acc, entity) => ({
...acc,
@@ -42,13 +41,11 @@ export function MergeDialog() {
{} as GraphNode
)
}
- const merge = {
- ...old,
- ...priorityEntity
- }
- setOld(old)
- setPreview(merge)
- }, [selectedNodes, priorityIndex, setPreview])
+ }, [selectedNodes, priorityEntity])
+ const preview = useMemo<GraphNode | null>(() => {
+ if (!old || !priorityEntity) return null
+ return { ...old, ...priorityEntity }
+ }, [old, priorityEntity])
const handleSubmit = async (e: { preventDefault: () => void }) => {
e.preventDefault()
diff --git a/flowsint-app/src/components/sketches/graph/hooks/use-quick-add.ts b/flowsint-app/src/components/sketches/graph/hooks/use-quick-add.ts
index 280f514f..8873f505 100644
--- a/flowsint-app/src/components/sketches/graph/hooks/use-quick-add.ts
+++ b/flowsint-app/src/components/sketches/graph/hooks/use-quick-add.ts
@@ -44,14 +44,27 @@ export const useQuickAdd = (sketchId?: string) => {
const addNode = useGraphStore((s) => s.addNode)
const replaceNode = useGraphStore((s) => s.replaceNode)
- // Detect type when debounced text changes
- useEffect(() => {
- if (!debouncedText.trim() || !state.active) {
+ // Reset detection immediately when there's no text or quick-add isn't
+ // active — adjusted during render rather than in an effect.
+ const shouldDetect = Boolean(debouncedText.trim()) && state.active
+ const [prevShouldDetect, setPrevShouldDetect] = useState(shouldDetect)
+ if (shouldDetect !== prevShouldDetect) {
+ setPrevShouldDetect(shouldDetect)
+ if (!shouldDetect) {
setState((prev) => ({ ...prev, detection: null, loading: false }))
- return
}
+ }
+
+ // Detect type when debounced text changes
+ useEffect(() => {
+ if (!shouldDetect) return
let cancelled = false
+ // Kicking off a loading flag synchronously at the start of a fetch
+ // effect is the standard pattern (see react.dev's own data-fetching
+ // examples) — not the "derived state from a prop" case this rule
+ // mainly targets.
+ // eslint-disable-next-line react-hooks/set-state-in-effect
setState((prev) => ({ ...prev, loading: true }))
sketchService
@@ -70,7 +83,7 @@ export const useQuickAdd = (sketchId?: string) => {
return () => {
cancelled = true
}
- }, [debouncedText, state.active])
+ }, [debouncedText, shouldDetect])
const open = useCallback((screenX: number, screenY: number, graphX: number, graphY: number) => {
setState({
diff --git a/flowsint-app/src/components/sketches/graph/index.tsx b/flowsint-app/src/components/sketches/graph/index.tsx
index d71831a6..b34923ba 100644
--- a/flowsint-app/src/components/sketches/graph/index.tsx
+++ b/flowsint-app/src/components/sketches/graph/index.tsx
@@ -1,4 +1,4 @@
-import React, { useCallback, useMemo, useEffect, useLayoutEffect, useState, useRef } from 'react'
+import React, { useCallback, useMemo, useEffect, useState, useRef } from 'react'
import { useShallow } from 'zustand/react/shallow'
import ForceGraph2D from 'react-force-graph-2d'
import { useGraphControls } from '@/stores/graph-controls-store'
@@ -391,13 +391,25 @@ const GraphViewer: React.FC<GraphViewerProps> = ({
// Bumped whenever render context deps change, to force cache invalidation in
// getOrCreateRC below even when globalScale alone doesn't. This used to be a
// ref mutated straight in a useMemo body — invalid (refs can't be written
- // during render) and only worked by accident. Real state + a layout effect
- // gets the same "one value per deps change" behavior the correct way.
+ // during render). Adjusted during render instead of via an effect: compare
+ // against the previous deps tuple and bump synchronously when they differ,
+ // same "one value per deps change" behavior, no extra render pass.
const [rcDepsVersion, setRcDepsVersion] = useState(0)
- useLayoutEffect(() => {
+ const [prevRcDeps, setPrevRcDeps] = useState([
+ highlightNodes,
+ highlightLinks,
+ selectedEdges,
+ theme
+ ])
+ if (
+ highlightNodes !== prevRcDeps[0] ||
+ highlightLinks !== prevRcDeps[1] ||
+ selectedEdges !== prevRcDeps[2] ||
+ theme !== prevRcDeps[3]
+ ) {
+ setPrevRcDeps([highlightNodes, highlightLinks, selectedEdges, theme])
setRcDepsVersion((v) => v + 1)
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [highlightNodes, highlightLinks, selectedEdges, theme])
+ }
const getOrCreateRC = useCallback(
(globalScale: number): RenderContext => {
diff --git a/flowsint-app/src/components/sketches/graph/node/actions/flag.tsx b/flowsint-app/src/components/sketches/graph/node/actions/flag.tsx
index 4e816f96..bcc24d2e 100644
--- a/flowsint-app/src/components/sketches/graph/node/actions/flag.tsx
+++ b/flowsint-app/src/components/sketches/graph/node/actions/flag.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useState, useEffect } from 'react'
+import { useCallback, useState } from 'react'
import { Button } from '@/components/ui/button'
import {
DropdownMenu,
@@ -28,10 +28,14 @@ export function NodeFlag({ sketchId, node }: { sketchId: string; node: GraphNode
const nodeId = node.id
const [flagValue, setFlagValue] = useState<flagColor | null>(node.nodeFlag)
- // Synchronize local state when props change (new node selected)
- useEffect(() => {
+ // Synchronize local state when props change (new node selected) —
+ // adjusted during render rather than in an effect.
+ const [prevKey, setPrevKey] = useState(`${nodeId}:${node.nodeFlag}`)
+ const syncKey = `${nodeId}:${node.nodeFlag}`
+ if (syncKey !== prevKey) {
+ setPrevKey(syncKey)
setFlagValue(node.nodeFlag)
- }, [nodeId, node.nodeFlag])
+ }
const handleUpdateFlag = useCallback(
async (value: string) => {
diff --git a/flowsint-app/src/components/sketches/import-preview.tsx b/flowsint-app/src/components/sketches/import-preview.tsx
index b5e371dd..e83bcce3 100644
--- a/flowsint-app/src/components/sketches/import-preview.tsx
+++ b/flowsint-app/src/components/sketches/import-preview.tsx
@@ -54,10 +54,13 @@ const DebouncedInput = memo(
const [localValue, setLocalValue] = useState(value)
const timeoutRef = useRef<NodeJS.Timeout>(null)
- // Sync from parent when value changes externally
- useEffect(() => {
+ // Sync from parent when value changes externally — adjusted during
+ // render rather than in an effect.
+ const [prevValue, setPrevValue] = useState(value)
+ if (value !== prevValue) {
+ setPrevValue(value)
setLocalValue(value)
- }, [value])
+ }
const handleChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
@@ -384,9 +387,10 @@ export function ImportPreview({
const [mappingIdsByType, setMappingIdsByType] = useState<Record<string, string[]>>({})
const [isInitialized, setIsInitialized] = useState(false)
- useEffect(() => {
- if (!actionItems || isInitialized) return
-
+ // One-time derivation once actionItems is available, guarded by
+ // isInitialized — a pure computation from already-available data, so it's
+ // adjusted during render rather than run as an effect.
+ if (actionItems && !isInitialized) {
const newMappingsById = new Map<string, EntityMapping>()
const newMappingIdsByType: Record<string, string[]> = {}
@@ -420,7 +424,7 @@ export function ImportPreview({
setMappingsById(newMappingsById)
setMappingIdsByType(newMappingIdsByType)
setIsInitialized(true)
- }, [actionItems, analysisResult.entities, fieldsByType, isInitialized])
+ }
const [paginationByType, setPaginationByType] = useState<
Record<string, { page: number; perPage: number }>
@@ -566,12 +570,10 @@ export function ImportPreview({
const typeNames = useMemo(() => Object.keys(mappingIdsByType), [mappingIdsByType])
const [activeTab, setActiveTab] = useState('')
- // Set initial active tab when types are loaded
- useEffect(() => {
- if (typeNames.length > 0 && !activeTab) {
- setActiveTab(typeNames[0])
- }
- }, [typeNames, activeTab])
+ // Set initial active tab when types are loaded — adjusted during render.
+ if (typeNames.length > 0 && !activeTab) {
+ setActiveTab(typeNames[0])
+ }
const includedCount = useMemo(() => {
let count = 0
diff --git a/flowsint-app/src/components/sketches/settings/settings.tsx b/flowsint-app/src/components/sketches/settings/settings.tsx
index cb55f447..bef9c1b2 100644
--- a/flowsint-app/src/components/sketches/settings/settings.tsx
+++ b/flowsint-app/src/components/sketches/settings/settings.tsx
@@ -215,9 +215,12 @@ function NodeColorsSection() {
const debounceTimers = useRef<Map<ItemType, NodeJS.Timeout>>(new Map())
// Sync local state with store when store changes externally (e.g., reset)
- useEffect(() => {
+ // — adjusted during render rather than in an effect.
+ const [prevStoreColors, setPrevStoreColors] = useState(storeColors)
+ if (storeColors !== prevStoreColors) {
+ setPrevStoreColors(storeColors)
setLocalColors(storeColors)
- }, [storeColors])
+ }
// Debounced color update function
const handleColorChange = useCallback(
@@ -451,8 +454,11 @@ export default function GlobalSettings() {
status: 'active'
})
- // Update form data when sketch data changes
- useEffect(() => {
+ // Update form data when sketch data changes — adjusted during render
+ // rather than in an effect.
+ const [prevSketch, setPrevSketch] = useState(sketch)
+ if (sketch !== prevSketch) {
+ setPrevSketch(sketch)
if (sketch) {
setFormData({
title: sketch.title || '',
@@ -460,7 +466,7 @@ export default function GlobalSettings() {
status: sketch.status || 'active'
})
}
- }, [sketch])
+ }
const updateMutation = useMutation({
mutationFn: async (updated: Partial<Sketch>) => {
diff --git a/flowsint-app/src/components/templates/json-viewer.tsx b/flowsint-app/src/components/templates/json-viewer.tsx
index b37fb509..d7137898 100644
--- a/flowsint-app/src/components/templates/json-viewer.tsx
+++ b/flowsint-app/src/components/templates/json-viewer.tsx
@@ -1,4 +1,3 @@
-import { useEffect, useState } from 'react'
import MonacoEditor from '@monaco-editor/react'
import { useTheme } from '@/components/theme-provider'
@@ -10,18 +9,11 @@ interface JsonViewerProps {
function useResolvedTheme() {
const { theme } = useTheme()
- const [resolvedTheme, setResolvedTheme] = useState<'dark' | 'light'>('dark')
-
- useEffect(() => {
- if (theme === 'system') {
- const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches
- setResolvedTheme(isDark ? 'dark' : 'light')
- } else {
- setResolvedTheme(theme as 'dark' | 'light')
- }
- }, [theme])
-
- return resolvedTheme
+ // Pure derived value — no state/effect needed, just recompute each render.
+ if (theme === 'system') {
+ return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
+ }
+ return theme as 'dark' | 'light'
}
export function JsonViewer({ data, height = '100%', className }: JsonViewerProps) {
diff --git a/flowsint-app/src/components/templates/yaml-editor.tsx b/flowsint-app/src/components/templates/yaml-editor.tsx
index 97ccd6dc..e7e59b4f 100644
--- a/flowsint-app/src/components/templates/yaml-editor.tsx
+++ b/flowsint-app/src/components/templates/yaml-editor.tsx
@@ -1,4 +1,4 @@
-import { useRef, useCallback, useEffect, useState } from 'react'
+import { useRef, useCallback } from 'react'
import MonacoEditor, { OnMount, OnChange } from '@monaco-editor/react'
import type { editor, Uri } from 'monaco-editor'
import { useTheme } from '@/components/theme-provider'
@@ -12,18 +12,11 @@ interface YamlEditorProps {
function useResolvedTheme() {
const { theme } = useTheme()
- const [resolvedTheme, setResolvedTheme] = useState<'dark' | 'light'>('dark')
-
- useEffect(() => {
- if (theme === 'system') {
- const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches
- setResolvedTheme(isDark ? 'dark' : 'light')
- } else {
- setResolvedTheme(theme as 'dark' | 'light')
- }
- }, [theme])
-
- return resolvedTheme
+ // Pure derived value — no state/effect needed, just recompute each render.
+ if (theme === 'system') {
+ return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
+ }
+ return theme as 'dark' | 'light'
}
export function YamlEditor({ value, onChange, onValidate, readOnly = false }: YamlEditorProps) {
diff --git a/flowsint-app/src/components/tutorial/tutorial-provider.tsx b/flowsint-app/src/components/tutorial/tutorial-provider.tsx
index 607e7e51..7f44ac72 100644
--- a/flowsint-app/src/components/tutorial/tutorial-provider.tsx
+++ b/flowsint-app/src/components/tutorial/tutorial-provider.tsx
@@ -64,6 +64,11 @@ export function TutorialProvider({ children }: TutorialProviderProps) {
setStepIndex(0)
}, [])
+ // Not restructured like the rest of this pass: <Joyride> is never actually
+ // rendered below (see the no-unused-vars fix elsewhere in this file), so
+ // this whole effect is dead in practice. Not worth the risk of subtly
+ // changing timing on a feature nobody can currently see run.
+ /* eslint-disable react-hooks/set-state-in-effect */
useEffect(() => {
const currentPath = location.pathname
const routeSteps = getStepsForRoute(currentPath)
@@ -82,6 +87,7 @@ export function TutorialProvider({ children }: TutorialProviderProps) {
setRun(false)
}
}, [location.pathname, getCompletedRoutes])
+ /* eslint-enable react-hooks/set-state-in-effect */
const handleJoyrideCallback = useCallback(
(data: CallBackProps) => {
diff --git a/flowsint-app/src/components/ui/carousel.tsx b/flowsint-app/src/components/ui/carousel.tsx
index a6bd56a2..0ecb85a0 100644
--- a/flowsint-app/src/components/ui/carousel.tsx
+++ b/flowsint-app/src/components/ui/carousel.tsx
@@ -89,9 +89,16 @@ function Carousel({
setApi(api)
}, [api, setApi])
+ // Initial scroll-state sync, adjusted during render rather than in the
+ // effect below (which now only subscribes to future changes).
+ const [prevApi, setPrevApi] = React.useState(api)
+ if (api !== prevApi) {
+ setPrevApi(api)
+ if (api) onSelect(api)
+ }
+
React.useEffect(() => {
if (!api) return
- onSelect(api)
api.on('reInit', onSelect)
api.on('select', onSelect)
diff --git a/flowsint-app/src/hooks/use-events.ts b/flowsint-app/src/hooks/use-events.ts
index c61fc325..328b926b 100644
--- a/flowsint-app/src/hooks/use-events.ts
+++ b/flowsint-app/src/hooks/use-events.ts
@@ -22,10 +22,13 @@ export function useEvents(sketch_id: string | undefined) {
setLiveLogs([]) // Pour éviter les doublons dans les logs live
}
- // Reset live logs when sketch_id changes
- useEffect(() => {
+ // Reset live logs when sketch_id changes — adjusted during render rather
+ // than in an effect.
+ const [prevSketchId, setPrevSketchId] = useState(sketch_id)
+ if (sketch_id !== prevSketchId) {
+ setPrevSketchId(sketch_id)
setLiveLogs([])
- }, [sketch_id])
+ }
useEffect(() => {
if (!sketch_id || !token) return
diff --git a/flowsint-app/src/hooks/use-mobile.ts b/flowsint-app/src/hooks/use-mobile.ts
index 4331d5c5..ce23d94c 100644
--- a/flowsint-app/src/hooks/use-mobile.ts
+++ b/flowsint-app/src/hooks/use-mobile.ts
@@ -3,7 +3,9 @@ import * as React from 'react'
const MOBILE_BREAKPOINT = 768
export function useIsMobile() {
- const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
+ // Computed synchronously at init — no need to also set it in the effect
+ // below, which only needs to subscribe to future changes.
+ const [isMobile, setIsMobile] = React.useState(() => window.innerWidth < MOBILE_BREAKPOINT)
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
@@ -11,9 +13,8 @@ export function useIsMobile() {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
}
mql.addEventListener('change', onChange)
- setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
return () => mql.removeEventListener('change', onChange)
}, [])
- return !!isMobile
+ return isMobile
}
diff --git a/flowsint-app/src/routes/_auth.dashboard.custom-types.$typeId.tsx b/flowsint-app/src/routes/_auth.dashboard.custom-types.$typeId.tsx
index 986a5734..5d75e4a6 100644
--- a/flowsint-app/src/routes/_auth.dashboard.custom-types.$typeId.tsx
+++ b/flowsint-app/src/routes/_auth.dashboard.custom-types.$typeId.tsx
@@ -1,6 +1,6 @@
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
-import { useState, useEffect, useCallback } from 'react'
+import { useState, useCallback } from 'react'
import { Button } from '@/components/ui/button'
import { customTypeService, CustomType } from '@/api/custom-type-service'
import { toast } from 'sonner'
@@ -47,6 +47,23 @@ function CustomTypeEditor() {
const [fields, setFields] = useState<SchemaField[]>([])
const [showPreview, setShowPreview] = useState(true)
+ const parseSchemaToFields = (schema: any) => {
+ const properties = schema.properties || {}
+ const required = schema.required || []
+ const parsedFields: SchemaField[] = Object.entries(properties).map(
+ ([key, value]: [string, any]) => ({
+ id: Math.random().toString(36).substr(2, 9),
+ key,
+ title: value.title || key,
+ type: value.type || 'string',
+ format: value.format,
+ description: value.description,
+ required: required.includes(key)
+ })
+ )
+ setFields(parsedFields)
+ }
+
// Hooks
const { actionItems, isLoading: actionLoading } = useActionItems()
@@ -73,9 +90,12 @@ function CustomTypeEditor() {
])
}, [])
- useEffect(() => {
+ // Adjusted during render rather than in an effect.
+ const [prevExistingType, setPrevExistingType] = useState(existingType)
+ if (existingType !== prevExistingType) {
+ setPrevExistingType(existingType)
if (existingType) {
- setName(existingType.name)
+ setName(existingType.name.replaceAll(' ', ''))
setDescription(existingType.description || '')
setStatus(existingType.status === 'archived' ? 'draft' : existingType.status)
setCategory(existingType.category || 'custom_types_category')
@@ -85,27 +105,6 @@ function CustomTypeEditor() {
} else if (isNew) {
addField()
}
- }, [existingType, isNew, addField])
-
- useEffect(() => {
- setName(name.replaceAll(' ', ''))
- }, [name])
-
- const parseSchemaToFields = (schema: any) => {
- const properties = schema.properties || {}
- const required = schema.required || []
- const parsedFields: SchemaField[] = Object.entries(properties).map(
- ([key, value]: [string, any]) => ({
- id: Math.random().toString(36).substr(2, 9),
- key,
- title: value.title || key,
- type: value.type || 'string',
- format: value.format,
- description: value.description,
- required: required.includes(key)
- })
- )
- setFields(parsedFields)
}
const fieldsToSchema = () => {
@@ -279,7 +278,7 @@ function CustomTypeEditor() {
<div className="flex-1 space-y-2 min-w-0">
<input
value={name}
- onChange={(e) => setName(e.target.value)}
+ onChange={(e) => setName(e.target.value.replaceAll(' ', ''))}
placeholder="Untitled type"
className="w-full text-3xl font-bold bg-transparent border-none outline-none placeholder:text-muted-foreground/30 text-foreground tracking-tight"
/>
diff --git a/flowsint-app/src/routes/_auth.dashboard.profile.tsx b/flowsint-app/src/routes/_auth.dashboard.profile.tsx
index fa36af71..a65c6f41 100644
--- a/flowsint-app/src/routes/_auth.dashboard.profile.tsx
+++ b/flowsint-app/src/routes/_auth.dashboard.profile.tsx
@@ -1,5 +1,5 @@
import { createFileRoute } from '@tanstack/react-router'
-import { useState, useEffect } from 'react'
+import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { authService } from '@/api/auth-service'
import { Button } from '@/components/ui/button'
@@ -31,7 +31,10 @@ function ProfilePage() {
avatar_url: ''
})
- useEffect(() => {
+ // Adjusted during render rather than in an effect.
+ const [prevProfile, setPrevProfile] = useState(profile)
+ if (profile !== prevProfile) {
+ setPrevProfile(profile)
if (profile) {
setForm({
first_name: profile.first_name ?? '',
@@ -39,7 +42,7 @@ function ProfilePage() {
avatar_url: profile.avatar_url ?? ''
})
}
- }, [profile])
+ }
const queryClient = useQueryClient()