🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
chore(AGENTS.md, skills): Update AGENTS.md to not use 'useEffect' unless its a valid case, add skill to refactor existing components (#15021)
Lysander Kiesel534b92d7a1ff
diff --git a/.agents/skills/frontend-large-feature-architecture/SKILL.md b/.agents/skills/frontend-large-feature-architecture/SKILL.mdindex 4df7fc5a9a..4ec3c448ca 100644--- a/.agents/skills/frontend-large-feature-architecture/SKILL.md+++ b/.agents/skills/frontend-large-feature-architecture/SKILL.md@@ -87,6 +87,9 @@ changing field does not rerender unrelated UI.Complex user workflows should live in `actions/*.ts` files or store actions.The component wires hooks and passes dependencies; the action owns the workflow.+For a complete effect audit or component-splitting recipes, use+[`../refactor-react-effects/SKILL.md`](../refactor-react-effects/SKILL.md).+## When To Read References- For the core big-feature rules and migration reality, readdiff --git a/.agents/skills/frontend-large-feature-architecture/references/big-feature-rules.md b/.agents/skills/frontend-large-feature-architecture/references/big-feature-rules.mdindex 40b04940eb..686f885322 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@@ -66,9 +66,10 @@ step-by-step controller path, read `controller-migration.md`.## Effects And Actions-Effects are for subscriptions, observers, imperative third-party APIs,-one-time initialization, and cleanup. Keep them in containers or feature hooks,-not view components. If an effect writes state repeatedly, make the store action+Effects are for named external-system integrations: subscriptions, observers,+browser event listeners, timers, and imperative third-party APIs, plus their+cleanup. Keep them in containers or feature hooks, not view+components. If an effect writes state repeatedly, make the store actionidempotent.Complex actions should be callable without rendering a component. Put workflowsdiff --git a/.agents/skills/frontend-large-feature-architecture/references/controller-migration.md b/.agents/skills/frontend-large-feature-architecture/references/controller-migration.mdindex 1288916d50..31b780e6cc 100644--- a/.agents/skills/frontend-large-feature-architecture/references/controller-migration.md+++ b/.agents/skills/frontend-large-feature-architecture/references/controller-migration.md@@ -107,8 +107,8 @@ migration, not proof that the whole surface is healthy.- Page components no longer rebuild columns, filters, row wrappers, and actioncallbacks for unrelated row-level changes.- Expensive rows/cells are view-only behind narrow containers.-- Effects are integration boundaries or one-time initialization, not ordinary- data derivation.+- Effects are external-system integration boundaries, not initialization or+ ordinary data derivation.- Complex workflows can be called without rendering the page.- The feature README tells the next developer what has improved, what remainsspread, and what the next improvement should target.diff --git a/.agents/skills/refactor-react-effects/SKILL.md b/.agents/skills/refactor-react-effects/SKILL.mdnew file mode 100644index 0000000000..926b0a178a--- /dev/null+++ b/.agents/skills/refactor-react-effects/SKILL.md@@ -0,0 +1,159 @@+---+name: refactor-react-effects+description: |+ Refactor avoidable React useEffect usage in Langfuse frontend code. Use when+ adding, reviewing, or removing effects; initializing forms or local UI state+ from query data; synchronizing client and server state; moving mutations or+ async workflows out of components; cleaning every effect from a frontend+ submodule; or reviewing whether an effect has a valid external-system owner.+---++# Refactor React Effects++Do not add `useEffect` by default. Use it only to synchronize a component with+a concrete system outside React. If there is no external system, remove the+effect.++Before adding or retaining an effect, answer all of these questions:++1. Which external system is being synchronized?+2. What starts or updates the synchronization?+3. What cleanup, if any, prevents leaks or duplicate subscriptions?+4. Why can an event handler, query API, render derivation, conditional mount,+ or existing integration hook not own the behavior?++If the first question has no concrete answer, do not use an effect.++## Required Context++- Read `web/AGENTS.md` and the nearest package guidance before changing web+ code.+- For large features, local Zustand stores, tables, or controller components,+ also read+ [`../frontend-large-feature-architecture/SKILL.md`](../frontend-large-feature-architecture/SKILL.md).+- Read+ [`references/refactoring-patterns.md`](references/refactoring-patterns.md)+ before implementing a refactor.++## Decision Rules++Apply these rules in order:++1. **Derive during render.** Compute values from current props, query data, and+ client state instead of storing a synchronized copy.+2. **Gate on required data.** If a form or UI cannot initialize correctly+ without query data, let a parent own loading/error handling. Mount a child+ only after the data exists and pass guaranteed initial values to its lazy+ `useState` initializer.+3. **Make reset semantics explicit.** Use a `key` to remount for a new entity+ only when discarding the old local draft is intended. Use an explicit user+ action for refresh/reset when drafts must not be overwritten silently.+4. **Run actions from events.** Put submit, mutation, navigation, notification,+ and multi-step async workflows in event handlers, `actions/*.ts`, or store+ actions. Pass a React Query client, mutation callback, or vanilla Zustand+ store as a dependency; never call React hooks from those actions.+5. **Keep real integration effects.** Subscriptions, observers, browser event+ listeners, timers, and imperative third-party APIs may need an effect. Make+ setup and cleanup symmetrical and keep the effect in a narrow integration+ hook or container. In a direct-effect-free module, use a pre-existing,+ centrally owned integration hook. Do not create a feature-local wrapper just+ to hide `useEffect`.++Presume that an effect which writes React or Zustand state from props or query+data is removable. Do not evade the design problem by switching to+`useLayoutEffect`, suppressing dependency lint, hiding the same synchronization+in a custom hook, or adding an ESLint disable.++## Fast Smell Test++Refactor when any of these shapes appear:++- `useEffect(() => setX(deriveFromY(y)), [y])`;+- fetch data, then mirror it with `setState`;+- set a flag, let an effect perform the action, then clear the flag;+- chain effects where one state write triggers the next effect;+- reset local state because an ID or prop changed;+- guard an integration inside an effect when the component could mount only+ after the precondition is true.++## Workflow++### 1. Establish the Behavior Boundary++Identify the state owner, query owner, user events, external systems, and+loading/error states. For a bug fix, add the failing test first and confirm it+fails. For a behavior-preserving migration, reuse existing coverage where it+protects the relevant behavior; add focused coverage only for a meaningful+behavior risk such as draft preservation, entity changes, refetches, submits,+or cleanup. Do not add tests that inspect source code or merely assert that a+hook is absent. Use behavior tests and the effect inventory instead.++### 2. Inventory Every Effect++Search the full target module, including tests and stories:++```bash+rg -n '\b(use(?:Layout)?Effect|React\.use(?:Layout)?Effect)\b' 'web/src/features/<feature>'+```++Classify every result as:++- render derivation;+- query-to-local-state initialization;+- client/server state synchronization;+- user-event or async workflow;+- external-system integration;+- test-only harness behavior.++Do not refactor from a raw count alone. Record what triggers each effect, what+it writes or controls, and the replacement pattern.++### 3. Refactor One Semantic Seam at a Time++Prefer this order:++1. replace redundant state with pure derivation;+2. split data-owning parents from stateful children;+3. move event-driven work to handlers or external actions;+4. isolate unavoidable integrations in narrow hooks;+5. remove dead state, guards, dependencies, and imports.++Keep user-visible behavior stable. Avoid bundling unrelated file moves, visual+changes, and state architecture changes into the same slice.++### 4. Complete a Submodule Migration++Repeat the inventory after each slice. Before declaring a submodule clean:++- account for every original effect;+- confirm no effect merely moved behind a wrapper hook;+- confirm refetches do not overwrite local edits;+- confirm entity changes have deliberate preserve/reset semantics;+- confirm complex actions are callable without rendering the feature;+- document any real external integration effect that remains outside the+ refactoring target.++Do not add or modify effect-specific ESLint rules or pre-commit checks as part+of this workflow. Treat enforcement policy as separate, explicitly requested+work.++### 5. Verify++Run, at minimum:++- focused client tests for the changed behavior;+- ESLint on the migrated path, then `pnpm --filter web run lint`;+- type checking when state or action interfaces changed;+- a real-browser review for user-visible flows, using seeded data where+ applicable;+- the effect inventory again to prove the intended scope is clean.++Report the exact command summary lines and any retained effects with their+external-system rationale.++## Output Format++Return valid Markdown. For module audits, include a compact table with the+effect location, classification, replacement, and status. Check headings,+lists, links, tables, backticks, and code fences for valid Markdown syntax+before returning the report.diff --git a/.agents/skills/refactor-react-effects/agents/openai.yaml b/.agents/skills/refactor-react-effects/agents/openai.yamlnew file mode 100644index 0000000000..80259e3e33--- /dev/null+++ b/.agents/skills/refactor-react-effects/agents/openai.yaml@@ -0,0 +1,4 @@+interface:+ display_name: "Refactor React Effects"+ short_description: "Replace avoidable React effects safely"+ default_prompt: "Use $refactor-react-effects to remove avoidable useEffect calls from this frontend module while preserving behavior."diff --git a/.agents/skills/refactor-react-effects/references/refactoring-patterns.md b/.agents/skills/refactor-react-effects/references/refactoring-patterns.mdnew file mode 100644index 0000000000..edf9186c1b--- /dev/null+++ b/.agents/skills/refactor-react-effects/references/refactoring-patterns.md@@ -0,0 +1,155 @@+# React Effect Refactoring Patterns++Use the smallest pattern that makes ownership and lifecycle explicit.++## Gate Required Data, Then Initialize the Child++Do not mount a stateful form with missing defaults and repair it after paint.+Let the query-owning parent render the loading/error state. Mount the form only+with complete initial values.++```tsx+function UserFormContainer({ userId }: { userId: string }) {+ const userQuery = api.users.byId.useQuery({ userId });++ if (userQuery.isPending) return <Spinner />;+ if (userQuery.isError) return <ErrorPage />;++ const initialValues = toUserFormValues(userQuery.data);++ return <UserForm key={userQuery.data.id} initialValues={initialValues} />;+}++function UserForm({ initialValues }: { initialValues: UserFormValues }) {+ const [values, setValues] = useState(() => initialValues);++ return <UserFields values={values} onChange={setValues} />;+}+```++The `key` expresses that changing to another user discards the previous draft.+Do not include a query update timestamp or version in the key unless every+refetch should intentionally discard edits. If users must choose when to adopt+fresh server values, expose a reset/refresh action instead.++## Derive Valid Client State from Server State++Keep the user's stored intent and derive whether it is currently valid. Do not+overwrite a selection store every time query data changes.++```tsx+const selectedUserId = useUserStore((state) => state.selectedUserId);+const selectedUser = users.find((user) => user.id === selectedUserId) ?? null;+```++This avoids a synchronization effect and preserves enough information to show+an invalid selection or restore it if the server value reappears. Expose the+derived value through one selector or custom hook so callers do not bypass the+validation rule accidentally.++## Compute Redundant Values During Render++```tsx+// Avoid: useEffect(() => setFullName(`${first} ${last}`), [first, last]);+const fullName = `${first} ${last}`;+```++Extract an expensive or complicated transformation into a pure function and+test it directly. Add memoization only when measurement shows that the pure+calculation is expensive or referential stability is required by a consumer.++## Put User-Triggered Work in an Action++Do not encode “when this flag becomes true, submit” as state plus an effect.+Call the workflow from the event that caused it.++```ts+type SaveWidgetDependencies = {+ store: WidgetStore;+ queryClient: QueryClient;+ mutateAsync: (input: SaveWidgetInput) => Promise<Widget>;+};++export async function saveWidget({+ store,+ queryClient,+ mutateAsync,+}: SaveWidgetDependencies) {+ const input = selectWidgetInput(store.getState());+ const widget = await mutateAsync(input);++ store.getState().markSaved(widget.id);+ await queryClient.invalidateQueries({ queryKey: ["widgets"] });+}+```++The component may use hooks to obtain `mutateAsync` or the query client, then+pass those dependencies to the action from `onClick` or `onSubmit`. A vanilla+Zustand store can be read directly by the action. The action itself must not+call hooks.++## Use Query APIs for Server Data++Do not fetch server data in an effect and mirror `loading`, `error`, and `data`+into local state when tRPC/React Query can own that lifecycle. Keep query data+as server state and derive render values from it.++For imperative work that must happen after a mutation, keep the sequence in the+mutation callback or the named action invoked by the event. Do not introduce a+“mutation completed” flag that another effect watches.++## Reset State Through Identity or an Explicit Event++When local state belongs to a particular entity, choose one behavior:++- preserve the draft while background data refetches;+- remount a keyed child when entity identity changes;+- reset from a deliberate cancel/reset/reload event;+- eliminate local state and make the server/query value the source of truth.++Do not let an effect choose implicitly, because it will often overwrite user+input on background refetch.++## Retain Only External-System Synchronization++An effect is appropriate when the component must connect to something React+does not control:++```tsx+useEffect(() => {+ const unsubscribe = externalStore.subscribe(handleChange);+ return unsubscribe;+}, [externalStore, handleChange]);+```++Other legitimate examples include `ResizeObserver`, browser event listeners,+timers, and imperative third-party widgets. Prefer existing subscription hooks+such as `useSyncExternalStore` when they model the integration more directly.+Keep setup and cleanup symmetrical, and do not mix ordinary data derivation+into the integration effect.++## Prefer Conditional Mounting for External Integrations++If an external integration should exist only after a precondition is met, make+that precondition a component boundary instead of a guard inside an effect.++```tsx+function PlayerArea({ ready }: { ready: boolean }) {+ return (+ <>+ <PlayerShell ready={ready} />+ {ready ? <PlayerInstance /> : null}+ </>+ );+}+```++The integration component now has one lifecycle: mount means connect; unmount+means disconnect. A `key` can provide a fresh lifecycle when an entity ID+changes.++## Stable References++- [React: You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect)+- [TkDodo: Deriving Client State from Server State](https://tkdodo.eu/blog/deriving-client-state-from-server-state)+- [Alvin Sng: Why we banned React's useEffect](https://x.com/alvinsng/article/2033969062834045089)diff --git a/web/AGENTS.md b/web/AGENTS.mdindex e921dd3f11..3ad7558b5a 100644--- a/web/AGENTS.md+++ b/web/AGENTS.md@@ -65,6 +65,8 @@ Use root [AGENTS.md](../AGENTS.md) for monorepo-level rules.- Large frontend feature, virtualized-list, local state, and Reacteffect-free data-flow architecture:[`../.agents/skills/frontend-large-feature-architecture/SKILL.md`](../.agents/skills/frontend-large-feature-architecture/SKILL.md)+- Avoidable React effect audits, refactors, and module migrations:+ [`../.agents/skills/refactor-react-effects/SKILL.md`](../.agents/skills/refactor-react-effects/SKILL.md)- React composition and component API design:[`web/.agents/skills/vercel-composition-patterns/SKILL.md`](.agents/skills/vercel-composition-patterns/SKILL.md)- React/Next.js performance and rendering best practices:@@ -100,6 +102,18 @@ action should emit an analytics event.must be installed, ask the user before doing so.- Tailwind is the default styling layer; use the shared palette and globals in`src/styles/globals.css`.+- Do not add `useEffect` by default. Use it only when a component must+ synchronize with a concrete system outside React, such as a subscription,+ browser event listener, observer, timer, or imperative third-party API.+ Before writing an effect, name that external system and its setup/cleanup+ lifecycle. If there is no external system, do not use an effect. In+ particular, do not use effects to derive render state, mirror props or query+ data into local state, react to user actions, or reset state when an ID+ changes. Derive during render, run work in the initiating event handler, use+ query APIs for server state, or mount a keyed child once required data is+ available. Do not evade this rule with `useLayoutEffect`, a custom wrapper+ hook, an ESLint suppression, or disabled dependency checks. Use+ `../.agents/skills/refactor-react-effects/SKILL.md` for effect work.- In flex layouts, prefer `gap-*` over margin-based `space-x-*`/`space-y-*`.- Treat `!` Tailwind classes as a smell. Step back and fix the owning layout,variant, or primitive before overriding with higher specificity.diff --git a/web/src/features/auth-credentials/components/ResetPasswordButton.tsx b/web/src/features/auth-credentials/components/ResetPasswordButton.tsxindex 9564f99216..be028f9b51 100644--- a/web/src/features/auth-credentials/components/ResetPasswordButton.tsx+++ b/web/src/features/auth-credentials/components/ResetPasswordButton.tsx@@ -1,7 +1,7 @@import { signIn, useSession } from "next-auth/react";import { Button } from "@/src/components/ui/button";import { Input } from "@/src/components/ui/input";-import { useEffect, useState } from "react";+import { useState } from "react";import { z } from "zod";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { env } from "@/src/env.mjs";@@ -20,15 +20,10 @@ export function RequestResetPasswordEmailButton({const [isEmailSent, setIsEmailSent] = useState(false);const [code, setCode] = useState("");const [isLoading, setIsLoading] = useState(false);- const [isValidEmail, setIsValidEmail] = useState(false);const [errorMessage, setErrorMessage] = useState<string | null>(null);const session = useSession();const capture = usePostHogClientCapture();-- useEffect(() => {- const isValidEmail = z.email().safeParse(email).success;- setIsValidEmail(isValidEmail);- }, [email]);+ const isValidEmail = z.email().safeParse(email).success;const handleResetPassword = async () => {if (!isValidEmail) return;