Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(agents): fold React-without-useEffect principles into frontend skill (LFE-10842) (#14994)

Nikita Kabardinead46b9c215e
diff --git a/.agents/AGENTS.md b/.agents/AGENTS.md
index 4b264cbd3c..dfc7d9380a 100644
--- a/.agents/AGENTS.md
+++ b/.agents/AGENTS.md
@@ -7,6 +7,10 @@ evaluating, and debugging AI applications.
- Read the minimal local context required for the task.
- Keep changes scoped and avoid unrelated refactors.
+- If you are about to write a `useEffect` β€” or sync fetched data into state, or
+ wire form initial values from loaded data β€” read
+ `.agents/skills/frontend-large-feature-architecture/SKILL.md` first. Most
+ such effects should not exist.
- For bug fixes, write the failing test first, confirm it fails, then fix the
bug. If the bug depends on a data shape, pause and ask: can
`pnpm run seed` prefill that shape locally? If not, consider extending a
diff --git a/.agents/skills/frontend-large-feature-architecture/SKILL.md b/.agents/skills/frontend-large-feature-architecture/SKILL.md
index bf58aaab7f..4df7fc5a9a 100644
--- a/.agents/skills/frontend-large-feature-architecture/SKILL.md
+++ b/.agents/skills/frontend-large-feature-architecture/SKILL.md
@@ -4,7 +4,9 @@ description: |
Use when building, changing, or refactoring large Langfuse frontend features,
virtualized lists, large tables, controller components, local feature state,
Zustand stores, row selection, high-frequency UI state, or
- rendering-performance issues.
+ rendering-performance issues. Also read BEFORE writing any useEffect
+ (especially one that syncs fetched data into state), wiring form
+ initialValues/defaultValues from loaded data, or adding useCallback/useMemo.
---
# Frontend Large Feature Architecture
@@ -27,6 +29,32 @@ boundaries, not the normal way to derive state.
For the full rules, read
[`references/big-feature-rules.md`](references/big-feature-rules.md).
+## React Without useEffect
+
+UI is a pure function of state. Do not use `useEffect` to derive, prepare, or
+sync data:
+
+- Derived values are computed in render (`const title = data?.name ?? ""`),
+ never mirrored into state by an effect. Client state that refers to server
+ data stores only the user's intent (an id) and derives the effective value
+ by merging with query data in render.
+- When loaded data seeds editable state, split the component: an outer
+ data-preparer/controller fetches and renders a loading state (prefer a
+ skeleton; `<Spinner />` as minimal fallback); the inner component receives
+ the loaded value as an `initialValue` prop and seeds `useState(initialValue)`.
+ Do not render UI before its data is ready.
+- Define a form only where all initial values are already prepared; if data is
+ still loading, the form lives deeper in the tree.
+- Complex actions live outside React as plain functions using the store or
+ query client β€” not inside components, not behind effects.
+- `useCallback`/`useMemo` are premature optimization; fix re-render problems by
+ splitting components, not memoizing.
+- `useEffect` is legitimate only for DOM/browser API integration: no (or
+ minimal) dependencies, one concern, and a cleanup function.
+
+For the golden example and full reasoning, read
+[`references/react-without-useeffect.md`](references/react-without-useeffect.md).
+
## Required Model
- The page/view owns lifecycle and creates feature-scoped dependencies.
@@ -42,8 +70,10 @@ For the full rules, read
- Shared `src/components/*` exports should stay context-free or receive
explicit props. Put view-scoped Zustand consumers in `src/features/*`.
- Large feature folders should have a concise `README.md` owner map.
-- Migrate real features through small PRs that improve one state boundary,
- action workflow, data-preparation seam, or render boundary.
+- Migrate real features toward this model whenever you touch them: improve
+ state boundaries, action workflows, data-preparation seams, and render
+ boundaries. Hundreds of legacy cases remain β€” do not preserve a legacy shape
+ just to keep a change small.
## Local Store Default
@@ -61,6 +91,10 @@ The component wires hooks and passes dependencies; the action owns the workflow.
- For the core big-feature rules and migration reality, read
[`references/big-feature-rules.md`](references/big-feature-rules.md).
+- For the React-without-useEffect model β€” derived values, gating render on
+ loaded data, `initialValue` props, forms, actions outside React, and why not
+ to memoize β€” read
+ [`references/react-without-useeffect.md`](references/react-without-useeffect.md).
- For virtualized lists, translated DOM, row measurement, and scroll rerenders,
read [`references/virtualized-lists.md`](references/virtualized-lists.md).
- For local feature stores and splitting large components, read
diff --git a/.agents/skills/frontend-large-feature-architecture/agents/openai.yaml b/.agents/skills/frontend-large-feature-architecture/agents/openai.yaml
index 2a1a8660fd..49b3cd3313 100644
--- a/.agents/skills/frontend-large-feature-architecture/agents/openai.yaml
+++ b/.agents/skills/frontend-large-feature-architecture/agents/openai.yaml
@@ -1,7 +1,7 @@
interface:
display_name: "Frontend Feature Architecture"
short_description: "Build, change, or refactor React features"
- default_prompt: "Use $frontend-large-feature-architecture to build, change, or refactor this large frontend surface with clear state ownership, stable subscriptions, and view-only render boundaries."
+ default_prompt: "Use $frontend-large-feature-architecture to build, change, or refactor this large frontend surface with clear state ownership, effect-free data flow, stable subscriptions, and view-only render boundaries."
policy:
allow_implicit_invocation: true
diff --git a/.agents/skills/frontend-large-feature-architecture/references/big-feature-rules.md b/.agents/skills/frontend-large-feature-architecture/references/big-feature-rules.md
index eee7043d67..40b04940eb 100644
--- a/.agents/skills/frontend-large-feature-architecture/references/big-feature-rules.md
+++ b/.agents/skills/frontend-large-feature-architecture/references/big-feature-rules.md
@@ -44,30 +44,25 @@ changing responsibilities and waking too much UI.
pure data preparation, a store action, or an explicit event handler.
9. Do not copy existing large Langfuse feature components as examples. Treat
them as legacy unless they follow this skill.
-10. Prefer small reliable PRs over a large rewrite. Each PR should improve one
- state boundary, action workflow, data-preparation seam, or render boundary,
- then update the feature README or migration note with the next slice.
+10. Follow the golden example in `react-without-useeffect.md`: gate render on
+ loaded data, seed state from `initialValue` props, and derive values in
+ render instead of syncing them with effects. When a change improves a
+ feature boundary, update the feature README or migration note with what
+ changed and the next slice.
## Migration Reality
Most large frontend features are not yet in the ideal shape. Traces,
observations, experiments, prompts, evals, datasets, and session views all have
-some controller-heavy surfaces. Do not copy an existing large component just
-because it works today. Treat it as a migration candidate and move it one
-state/action/data-preparation boundary at a time.
-
-For the step-by-step path, read `controller-migration.md`.
-
-## Small PR Policy
-
-A good big-feature PR is intentionally incomplete. It should change one
-semantic interaction and keep behavior stable: one selection boundary, one
-action workflow, one pure data-preparation helper, or one render boundary.
-
-Do not bundle file reorganization, state extraction, visual changes, and
-behavior fixes in the same PR unless the user explicitly asks for that scope.
-When a reorganization is needed, prefer a rename-only PR first or a later
-follow-up PR.
+controller-heavy surfaces, and there are hundreds of cases still to fix β€”
+including hundreds of `useEffect` calls that derive or sync state. Do not copy
+an existing large component just because it works today; treat it as a
+migration candidate. Do not scale ambition down either: broad, coherent
+improvements are welcome as long as each changed boundary is deliberate.
+
+The golden example β€” gate render on loaded data, seed state from props, keep
+actions outside React β€” is in `react-without-useeffect.md`. For the
+step-by-step controller path, read `controller-migration.md`.
## Effects And Actions
diff --git a/.agents/skills/frontend-large-feature-architecture/references/controller-migration.md b/.agents/skills/frontend-large-feature-architecture/references/controller-migration.md
index 685500119d..1288916d50 100644
--- a/.agents/skills/frontend-large-feature-architecture/references/controller-migration.md
+++ b/.agents/skills/frontend-large-feature-architecture/references/controller-migration.md
@@ -7,8 +7,9 @@ actions, and expensive rendering.
The target is clear ownership, not "everything in a store." Start from the
ownership baseline in `big-feature-rules.md`.
-Most existing features are not there yet. Migrate in narrow slices and keep
-behavior stable.
+Most existing features are not there yet, and there are hundreds of cases
+still to fix. Be explicit about which boundaries each change improves and what
+behavior changes on purpose.
## Realistic Migration Strategy
@@ -18,15 +19,16 @@ change safer than the previous one.
For each migration PR, write down:
- the current controller problem being targeted
-- the single state/action/data-preparation/render boundary being improved
-- what behavior must remain unchanged
+- the state/action/data-preparation/render boundaries being improved
+- what behavior changes on purpose and what must remain unchanged β€” a UI
+ simplification such as gating render behind a spinner is often the right
+ call (see `react-without-useeffect.md`)
- what instrumentation or tests prove the slice worked
- what still remains spread across the feature
-- the next recommended atomic slice
+- the next recommended slice
-This is how large features become managed features without review-hostile
-rewrites. The feature README is the living owner map; update it in place as the
-feature moves forward.
+This is how large features become managed features. The feature README is the
+living owner map; update it in place as the feature moves forward.
## Step-by-Step Path
@@ -39,12 +41,12 @@ feature moves forward.
selection, scroll, filter change, drawer open, form step change, or
saved-view change. Measure what rerenders, remounts, refetches, or
recalculates.
-4. **Choose one boundary.** Start with the smallest high-value boundary:
- selection, lazy-row state, batch action workflow, filter-target mapping,
- column/view state, wizard step state, or pure data preparation. Do not
- migrate everything at once.
+4. **Choose a boundary.** Start with a high-value boundary: selection,
+ lazy-row state, batch action workflow, filter-target mapping, column/view
+ state, wizard step state, or pure data preparation. Work boundary by
+ boundary, even when one change improves several.
5. **Choose the lightest tool.** A pure helper or action extraction may be the
- right first PR. Add a local store only when selective subscriptions or
+ right first move. Add a local store only when selective subscriptions or
per-mount persistence are needed.
6. **Create a local store instance when needed.** Use lazy `useState` in the
page/view:
@@ -109,7 +111,7 @@ migration, not proof that the whole surface is healthy.
data derivation.
- Complex workflows can be called without rendering the page.
- The feature README tells the next developer what has improved, what remains
- spread, and what the next small PR should target.
+ spread, and what the next improvement should target.
Avoid:
diff --git a/.agents/skills/frontend-large-feature-architecture/references/feature-readmes.md b/.agents/skills/frontend-large-feature-architecture/references/feature-readmes.md
index 95b4e2e912..686f97e630 100644
--- a/.agents/skills/frontend-large-feature-architecture/references/feature-readmes.md
+++ b/.agents/skills/frontend-large-feature-architecture/references/feature-readmes.md
@@ -69,21 +69,18 @@ Use an update-in-place style rather than a changelog. For example:
batch action workflow into an action file; split route/query glue from view
components.
-This makes small PRs reviewable while keeping the feature migration plan
-visible. Do not wait for a perfect reorganization before documenting the
+This keeps each improvement reviewable while keeping the feature migration
+plan visible. Do not wait for a perfect reorganization before documenting the
current state.
-## PR-Scale Guidance
+## Matching Updates To The Change
-Feature README updates should match the PR size:
+Feature README updates should match what actually changed:
-- For a small state/action extraction, add or update only the relevant
+- For a state/action extraction, add or update only the relevant
migration-state bullets.
- For a new feature folder structure, include the owner map and external
consumers before moving logic into the folder.
-- For a rename-only PR, document intended structure but avoid changing behavior.
-- For behavior PRs, avoid unrelated file moves unless they are required for the
- boundary being improved.
The README should help the next contributor avoid falling back into the same
large component, not argue that the migration is complete.
diff --git a/.agents/skills/frontend-large-feature-architecture/references/react-without-useeffect.md b/.agents/skills/frontend-large-feature-architecture/references/react-without-useeffect.md
new file mode 100644
index 0000000000..a4103aeb2b
--- /dev/null
+++ b/.agents/skills/frontend-large-feature-architecture/references/react-without-useeffect.md
@@ -0,0 +1,159 @@
+# React Without useEffect
+
+UI is a pure function of state. Almost every `useEffect` that derives,
+prepares, or syncs data should not exist. The codebase has hundreds of them
+(over 350 `useEffect` call sites in `web/src` at the time of writing), and
+agents reach for `useEffect` by default because their training data is full
+of it. Do not.
+This file is the golden example and the target shape. Treat every
+data-derivation effect you touch as a migration candidate.
+
+## Mental Model: State β†’ Frame
+
+Think of React as a game engine: the UI is a frame, rendered from state by a
+pure function. An effect that writes state breaks that model mechanically:
+React commits and paints a frame from incomplete state, the effect fires
+after paint, and a second render repairs the frame. Between those frames the
+user can act and async results can land, so the repair step races real input β€”
+this is where "the effect reset my form" bugs come from. Concurrent rendering
+(React 18+) makes the timing even less predictable, but the model was already
+broken: two renders and a repair step where one pure render should be.
+
+Keep render pure. Logic belongs where execution is synchronous and owned:
+event handlers, named actions, or plain derived values.
+
+## The #1 Anti-Pattern: Effects That Derive Or Prepare Data
+
+Real case, `web/src/features/monitors/pages/EditMonitorPage.tsx`:
+
+```tsx
+const [liveName, setLiveName] = useState("");
+useEffect(() => {
+ setLiveName(data?.name ?? "");
+}, [data?.name]);
+```
+
+An effect mirrors fetched data into local state. Now there are two sources of
+truth, a timing window between them, and a race: if the user edits the name
+before the query settles, the effect clobbers their input.
+
+Two fixes, depending on what the value is:
+
+- **Purely derived value** (never edited locally): compute it in render. No
+ state, no effect: `const title = data?.name ?? ""`.
+- **Loaded data seeding editable state** (this case): use the golden split
+ below.
+
+## The Golden Example: Split The Component, Gate Render On Load
+
+Split into two components. The outer one is a data preparer + controller: it
+fetches and renders a loading state while the query is pending β€” prefer a
+skeleton that matches the final layout; a `<Spinner />` is the minimal
+fallback. The inner one receives the loaded value as an `initialValue` prop
+and seeds `useState(initialValue)` β€” the value is guaranteed present and
+stable, and no effect can clobber it.
+
+```tsx
+// Outer: data preparer + controller. Do not render UI before its data is ready.
+function EditMonitorPage() {
+ const { data, isPending } = api.monitors.get.useQuery({ projectId, id });
+ if (isPending) return <Spinner />;
+ if (!data) return <ErrorPage title="Monitor not found" />;
+ return <EditMonitorForm key={data.id} initialMonitor={data} />;
+}
+
+// Inner: mounts only once data exists. Seeds state exactly once.
+function EditMonitorForm({ initialMonitor }: { initialMonitor: Monitor }) {
+ const [liveName, setLiveName] = useState(initialMonitor.name);
+ // ...
+}
+```
+
+This kills the whole class of typing-before-load races: there is no moment
+where the form exists without its data. The `key` remounts the inner component
+when the entity identity changes, so the seed stays honest.
+
+## Derive Client State From Server State
+
+When client state refers to server data β€” a selected row, an active id, a
+chosen option β€” store only the user's intent (the id) and derive the effective
+value during render by merging it with the query data:
+
+```tsx
+const selectedId = useFeatureStore((s) => s.selectedId);
+const selected = rows.find((r) => r.id === selectedId) ?? null;
+```
+
+Do not write an effect that validates or copies server data into the client
+store on refetch. Deriving keeps one source of truth per fact β€” the store owns
+intent, the query owns data β€” and the merge stays correct through loading,
+refetch, and invalidation. Wrap the merge in `useMemo` only when it is
+measurably expensive. (Pattern:
+[Deriving Client State from Server State](https://tkdodo.eu/blog/deriving-client-state-from-server-state).)
+
+## Forms
+
+Only define a form where all initial values are already prepared. If data is
+still loading, the form lives deeper in the tree: a `DataPreparerAndController`
+fetches, shows a loading state, then passes `initialValues` and `onSubmit` to a
+pure `FormComponent` that only renders fields and submits.
+
+Real case, `web/src/features/playground/page/components/CreateOrEditLLMToolDialog.tsx`:
+`useForm` is created at the top of the dialog with create-mode defaults, then a
+"populate form when in edit mode" effect calls `form.reset(...)` once the
+existing tool is available. The fix is structural, not a better effect: decide
+the `defaultValues` (create vs. edit) before rendering the form component, and
+render the form only when they are ready. The reset effect disappears.
+
+## Big Actions Live Outside React
+
+`queryClient` (React Query) and vanilla Zustand store instances are reachable
+outside the component tree β€” nothing forces a workflow through a hook or an
+effect. In the same dialog, `prettifyJson` and `handleDelete` are trapped
+inside the component because they close over form state and mutation hooks.
+Restructure so the dependencies live outside (the store, or a small passed-in
+dependency object), and the action becomes a plain, testable function.
+
+See `big-feature-rules.md` (Effects And Actions) and `local-feature-state.md`
+(Independent Actions) for the action shape.
+
+## When useEffect Is Legitimate
+
+An effect is for reaching things that exist outside React's render: the DOM
+and browser APIs. `document.addEventListener`/`removeEventListener`,
+observers, imperative third-party APIs, Web Audio (which also requires a user
+gesture). A healthy effect has: no dependencies (or minimal stable ones), one
+concern, and a cleanup function.
+
+## useCallback And useMemo Are Premature Optimization
+
+`useCallback` is `useMemo` for a function. Do not memoize before a confirmed,
+measured performance problem. Fix performance by splitting components and
+correcting re-render boundaries β€” splitting is itself a form of memoization.
+Needing memoization everywhere means the component re-renders too often, which
+means a state boundary is wrong. Fix the boundary.
+
+The exception is referential stability as a correctness requirement: when a
+callback or object is a dependency of a legitimate integration effect or a
+data-fetching hook, memoize it β€” or hoist it outside the component β€” so the
+dependency does not change identity every render and loop the effect. That is
+correctness, not optimization.
+
+## Prefer UI Solutions Over Code Solutions
+
+Many frontend problems have UI solutions, not code solutions. A loading state
+plus gated rendering deletes more complexity than a clever behavior-preserving
+refactor. Do not fear changing behavior to simplify: rendering a skeleton
+where the page previously showed a half-ready form is an improvement, not a
+regression. This is also why "write a characterization test, then refactor
+preserving behavior" rarely fits large frontend refactors β€” the target
+behavior is often the simpler one, not the current one.
+
+## The Vision
+
+Fetched data flows one way: query β†’ prepared data β†’ render, gated on
+readiness. State is seeded from props, edited by handlers, and never mirrored
+by effects. Actions are plain functions outside the tree. Effects that remain
+are thin DOM/browser integrations with cleanup. Hundreds of cases do not yet
+look like this β€” when you touch one, move it toward this shape rather than
+extending the effect.
diff --git a/web/AGENTS.md b/web/AGENTS.md
index e7041988da..e921dd3f11 100644
--- a/web/AGENTS.md
+++ b/web/AGENTS.md
@@ -62,7 +62,8 @@ Use root [AGENTS.md](../AGENTS.md) for monorepo-level rules.
- Shared browser-review workflow for user-visible frontend changes:
[`../.agents/skills/frontend-browser-review/SKILL.md`](../.agents/skills/frontend-browser-review/SKILL.md)
-- Large frontend feature, virtualized-list, and local state architecture:
+- Large frontend feature, virtualized-list, local state, and React
+ effect-free data-flow architecture:
[`../.agents/skills/frontend-large-feature-architecture/SKILL.md`](../.agents/skills/frontend-large-feature-architecture/SKILL.md)
- React composition and component API design:
[`web/.agents/skills/vercel-composition-patterns/SKILL.md`](.agents/skills/vercel-composition-patterns/SKILL.md)
@@ -75,9 +76,12 @@ Read these package-local skills before substantial frontend refactors when the
task involves component composition, reusable component APIs, rendering
performance, virtualized lists, local feature stores, bundle size,
React/Next.js performance patterns, or browser-based signoff of user-visible
-changes. When adding a meaningful user action (button, handler, form,
-mutation, feature surface), read the PostHog instrumentation skill and decide
-explicitly whether the action should emit an analytics event.
+changes. If you are about to write a `useEffect` or wire form initial values
+from loaded data, read the frontend-large-feature-architecture skill first β€”
+most effects that derive or sync state should not exist. When adding a
+meaningful user action (button, handler, form, mutation, feature surface),
+read the PostHog instrumentation skill and decide explicitly whether the
+action should emit an analytics event.
## Web Conventions