Przejdź do treści
Biblioteka skilli
Programowanie · Przegląd i audyt

no-use-effect

/no-use-effect

Ogranicza zbędne useEffect w React, kierując kod do stanu pochodnego, obsługi zdarzeń, formularzy, resetów przez key i bibliotek danych.

Repozytorium
skills ↗
Licencja
MIT
Ostatnia zmiana repozytorium
19.10.2026

Ocena i bezpieczeństwo

100/ 100Klasa: dobry
Format25 / 25
Frontmatter z nazwą i opisem, poprawna nazwa, opis do 1024 znaków, nazwa zgodna z folderem.
Odkrywalność25 / 25
Opis mówi, kiedy użyć skilla, ma sensowną długość i jest w 3. osobie.
Treść35 / 35
Co najmniej 150 słów i do 500 linii, nagłówki, listy kroków, przykłady albo kod.
Higiena15 / 15
Bez zaślepek typu TODO, bez ścieżek Windows, z licencją.
Ryzykobrak sygnałów w skanie
Pliki w paczce
2
Skrypty
0
Komentarze HTML
0
Adresy URL w SKILL.md
0
Przestarzałość

Brak sygnałów. Repozytorium zmienione 19.10.2026, bez odwołań do wycofanych modeli i API.

Licencja

MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.

Co robi i kiedy

Ogranicza zbędne useEffect w React, kierując kod do stanu pochodnego, obsługi zdarzeń, formularzy, resetów przez key i bibliotek danych.

Wyzwalacze z opisu

avoid useEffectremove useEffectyou might not need an effecteffect dependenciesuseEffectEventderived stateReact side effects
Oryginalny opis (EN)

Prevent unnecessary React `useEffect` usage by steering code toward derived state, event handlers and form Actions, `key`-based resets, `useSyncExternalStore`, `useEffectEvent`, and framework or query-library data APIs. Use when writing or reviewing React/Next.js components, refactoring effect-heavy code, or when a change introduces `useEffect`, `useLayoutEffect`, or dependency-array churn. Triggers on: "avoid useEffect", "remove useEffect", "you might not need an effect", "effect dependencies", "useEffectEvent", "derived state", "React side effects".

Jak działa

  1. Core Rule
  2. Replacement Patterns
  3. Anti-Patterns
  4. Review Checklist
  5. Team Policy
  6. References
Sekcje z nagłówków SKILL.md, w oryginale · 374 linii, 1 800 słów
Podgląd SKILL.md
---
name: no-use-effect
description: >-
  Prevent unnecessary React `useEffect` usage by steering code toward derived state,
  event handlers and form Actions, `key`-based resets, `useSyncExternalStore`,
  `useEffectEvent`, and framework or query-library data APIs. Use when writing or reviewing
  React/Next.js components, refactoring effect-heavy code, or when a change introduces
  `useEffect`, `useLayoutEffect`, or dependency-array churn. Triggers on: "avoid useEffect",
  "remove useEffect", "you might not need an effect", "effect dependencies",
  "useEffectEvent", "derived state", "React side effects".
---

# No useEffect

Treat raw `useEffect` as a last resort, not a default tool. Most component logic belongs in
render, event handlers, framework data APIs, or narrower React primitives.

This skill targets React 19.2+. It is based primarily on the React docs (`You Might Not Need an
Effect`, `Synchronizing with Effects`, `Separating Events from Effects`, `Removing Effect
Dependencies`), with supporting guidance from Dan Abramov, Kent C. Dodds, TkDodo, and team
practices that ban or heavily restrict raw `useEffect`.

## Core Rule

Before adding an Effect, answer this question:

"What external system am I synchronizing with, and why can't this be done during render, in an event handler, or with a more specific primitive?"

If you cannot name the external system, do not write the Effect.

External systems include:
- browser APIs and DOM subscriptions
- timers, sockets, observers, media APIs
- third-party widgets and imperative libraries
- network synchronization that truly happens because the component is visible

Not external systems:
- derived values from props or state
- event-driven actions like submit, save, buy, delete, notify
- resetting local state because props changed
- chaining state updates to trigger more state updates
- passing data upward just because a child rendered

## Replacement Patterns

### 1. Derive during render

Do not mirror props or state into more state.

```tsx
// Bad
const [fullName, setFullName] = useState("");
useEffect(() => {
  setFullName(`${firstName} ${lastName}`);
}, [firstName, lastName]);

// Good
const fullName = `${firstName} ${lastName}`;
```

Use this for filtered lists, labels, counts, booleans, selected objects, and other values that
can be computed from current inputs.

### 2. Memoize expensive pure work

If the calculation is slow, cache it with `useMemo`. Do not use an Effect that immediately
calls `setState` with a computed value.

```tsx
const visibleTodos = useMemo(() => getVisibleTodos(todos, filter), [todos, filter]);
```

First ask whether the work is actually expensive. If not, calculate it directly during render.
If the project uses React Compiler, it memoizes this for you; skip the manual `useMemo`.

### 3. Put user actions in event handlers

If the code runs because the user clicked, submitted, selected, dragged, or typed, keep it in
the corresponding handler.

```tsx
// Bad
useEffect(() => {
  if (shouldSubmit) {
    void saveForm(form);
  }
}, [shouldSubmit, form]);

// Good
async function handleSubmit() {
  await saveForm(form);
}
```

Never build "set flag -> Effect notices flag -> Effect does the real work" flows unless the
flag is synchronizing with a real external system.

For form submissions, React 19 Actions replace both the Effect and most hand-rolled pending
state. Pass a function to `<form action>`, and use `useActionState` when you need the result or
a pending flag:

```tsx
const [error, submitAction, isPending] = useActionState<string | null, FormData>(async (_prev, formData) => {
  const result = await saveForm(formData);
  return result.ok ? null : result.error;
}, null);

return (
  <form action={submitAction}>
    {/* fields */}
    <button disabled={isPending}>Save</button>
    {error && <p role="alert">{error}</p>}
  </form>
);
```

### 4. Reset identity with `key` when you want a fresh instance

If a component should become a brand-new instance when some identity changes, give it a
different `key`. React will unmount the old subtree and mount a new one, which resets all local
state below that point without an Effect.

```tsx
// Bad
function Profile({ userId }: { userId: string }) {
  const [comment, setComment] = useState("");

  useEffect(() => {
    setComment("");
  }, [userId]);

  return <input value={comment} onChange={(e) => setComment(e.target.value)} />;
}

// Good
function ProfilePage({ userId }: { userId: string }) {
  return <Profile key={userId} userId={userId} />;
}

function Profile({ userId }: { userId: string }) {
  const [comment, setComment] = useState("");
  return <input value={comment} onChange={(e) => setComment(e.target.value)} />;
}
```

Use this when the identity really changed: user, document, chat room, wizard step, or form
instance. Do not use it when you only want to tweak one field, because remounting resets the
entire subtree.

### 5. Lift state or control the component

If an Effect exists only to notify a parent after local state changed, the data model is usually
wrong. Prefer lifting state up or updating both sides in the same event.

```tsx
// Bad
function Toggle({ onChange }: { onChange: (next: boolean) => void }) {
  const [isOn, setIsOn] = useState(false);

  useEffect(() => {
    onChange(isOn);
  }, [isOn, onChange]);

  return <button onClick={() => setIsOn(!isOn)}>{isOn ? "On" : "Off"}</button>;
}

// Good
function Toggle({ isOn, onChange }: { isOn: boolean; onChange: (next: boolean) => void }) {
  return <button onClick={() => onChange(!isOn)}>{isOn ? "On" : "Off"}</button>;
}
```

### 6. Use `useSyncExternalStore` for external subscriptions

Use `useSyncExternalStore` when the source of truth lives outside React and changes over time.
This is React's built-in primitive for subscribing to external stores.

Good fits:
- browser APIs with a current value plus subscription events
- third-party or app-level stores outside React state
- reusable hooks like `useOnlineStatus()` or `useMediaQuery()`

The shape is:

```tsx
const value = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
```

Where:
- `subscribe` tells React how to listen for changes and return cleanup
- `getSnapshot` reads the current value from the external store
- `getServerSnapshot` provides the initial server and hydration value when SSR is involved

```tsx
// Bad
function useOnlineStatus() {
  const [isOnline, setIsOnline] = useState(true);

  useEffect(() => {
    function updateStatus() {
      setIsOnline(navigator.onLine);
    }

    updateStatus();
    window.addEventListener("online", updateStatus);
    window.addEventListener("offline", updateStatus);

    return () => {
      window.removeEventListener("online", updateStatus);
      window.removeEventListener("offline", updateStatus);
    };
  }, []);

  return isOnline;
}

// Good
const isOnline = useSyncExternalStore(subscribe, () => navigator.onLine, () => true);
```

Prefer this over hand-rolled subscription Effects in components.

Important caveats from the React docs:
- `getSnapshot` must return a stable cached value unless the store actually changed
- if `subscribe` changes identity every render, React will resubscribe every render
- if you support SSR, `getServerSnapshot` must match between server render and hydration

Do not use this for:
- normal component state that should live in `useState`, `useReducer`, or context
- derived values you can calculate during render
- user actions handled by event handlers
- one-time fetching
- general side effects that are not subscriptions

### 7. Fetch through the framework or a data library

Avoid raw fetch-in-Effect code in app components when a framework loader or query library is
available.

Preferred order:
1. framework data APIs (`Next.js`, `React Router`, server components, route loaders)
2. data libraries (`TanStack Query`, `SWR`)
3. `use(promise)` inside a `Suspense` boundary, when the promise comes from a server component, loader, or cache. Do not create the promise during render in a client component; it is recreated every render.
4. a focused custom hook
5. raw `useEffect` only if none of the above fit

If you must fetch in an Effect, handle cleanup so stale responses are ignored.

```tsx
// Bad
useEffect(() => {
  void fetchResults(query).then(setResults);
}, [query]);

// Good
useEffect(() => {
  let ignore = false;

  void fetchResults(query).then((next) => {
    if (!ignore) {
      setResults(next);
    }
  });

  return () => {
    ignore = true;
  };
}, [query]);
```

### 8. Move non-reactive logic into `useEffectEvent`

When an Effect must read a value but should not re-run when that value changes, put that read in
an Effect Event. It always sees the latest props and state and stays out of the dependency list.
This replaces the "latest ref" pattern (`callbackRef.current = callback`) and
`eslint-disable` on the dependency array.

```tsx
// Bad: changing theme reconnects the chat
useEffect(() => {
  const connection = createConnection(roomId);
  connection.on("connected", () => showNotification("Connected!", theme));
  connection.connect();
  return () => connection.disconnect();
}, [roomId, theme]);

// Good: only roomId re-synchronizes
const onConnected = useEffectEvent(() => {
  showNotification("Connected!", theme);
});

useEffect(() => {
  const connection = createConnection(roomId);
  connection.on("connected", onConnected);
  connection.connect();
  return () => connection.disconnect();
}, [roomId]);
```

Rules from the React docs:
- Call Effect Events only from Effects or other Effect Events. Never during render, from event
  handlers, or passed to children or other Hooks.
- Never list them in a dependency array. Their identity changes every render on purpose.
- Do not use them to hide a dependency that should re-run the Effect. If a value change should
  re-synchronize, keep it as a dependency.

### 9. Encapsulate unavoidable imperative synchronization

Sometimes an Effect is correct: sockets, observers, widgets, media controls, focus management,
layout measurement, or DOM APIs that must stay in sync with rendered output.

When that happens:
- keep the Effect tiny and specific
- name the external system in a comment or hook name
- include full cleanup
- prefer a custom hook over open-coded Effect logic in many components
- consider `useLayoutEffect` only for pre-paint measurement or visual correctness

```tsx
// Bad
function ChatRoom({ roomId }: { roomId: string }) {
  useEffect(() => {
    const connection = createConnection(roomId);
    connection.connect();
  }, [roomId]);
}

// Good
function useChatConnection(roomId: string) {
  useEffect(() => {
    const connection = createConnection(roomId);
    connection.connect();

    return () => {
      connection.disconnect();
    };
  }, [roomId]);
}
```

If your team bans raw `useEffect`, put these escape hatches behind approved hooks instead of
sprinkling Effects through feature code.

## Anti-Patterns

Treat these as red flags during authoring or review:
- `useEffect(() => setX(...), [...])` for derived state
- Effect only exists to call a function after a button click
- effect chains where one state update triggers another Effect and another render
- dependency arrays fought with `eslint-disable`, refs-as-flags, or intentionally stale closures
  (use `useEffectEvent` for the non-reactive part)
- synchronous `setState` at the top of an Effect (flagged by `react-hooks/set-state-in-effect`)
- object or function dependencies recreated every render without need
- child component fetching data and pushing it upward in an Effect
- mount-only initialization that should live in module scope, entrypoints, or framework boot code

## Review Checklist

Before accepting a new Effect, verify all of these:
- [ ] The code synchronizes with a real external system
- [ ] Derived render data, memoization, events and Actions, `key`, lifted state, and
      `useSyncExternalStore` were all considered first
- [ ] The dependency list is honest and complete; non-reactive reads live in `useEffectEvent`
- [ ] Setup and cleanup are symmetrical
- [ ] The Effect is idempotent under Strict Mode re-mounting
- [ ] Data fetching is not bypassing an existing framework or query abstraction
- [ ] The logic is small enough that a custom hook or helper name explains its purpose

## Team Policy

For teams trying to ban or heavily restrict raw `useEffect`, use this policy:

1. Do not introduce `useEffect` for derived state, events, or resets.
2. Prefer render-time derivation, event handlers, `key`, `useMemo`, and `useSyncExternalStore`.
3. Route data loading through the framework or an approved query library.
4. If an Effect is still necessary, hide it behind a narrowly named custom hook or document the
   external system and cleanup explicitly in review.
5. Enable the `recommended` preset of `eslint-plugin-react-hooks`. It includes
   `exhaustive-deps` and the compiler-backed rules such as `set-state-in-effect`.
6. Never silence `react-hooks/exhaustive-deps` to "make it work".

## References

For source material and further reading, see `references/sources.md`.
Pliki w paczce (2)
  • SKILL.md 13 KB
  • references/sources.md 3 KB

Wersje

RepozytoriumWynikLicencja
Ta strona · caidanw/skills100MIT
RIJUDEVx/agent-skills100MIT
fastrepl/anarlog100MIT
caidanw/skills100MIT

Migawka bazy z 13.11.2026 · wersja paczki 8336c433baf0 (skrót SHA-256 całej paczki)

Pobrania w ostatnich 30 dniach: 0 · ranking

Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.

Podobne skille

  • 100react-effects-audit
    Audytuje komponenty React i Next.js pod kątem zbędnego lub niebezpiecznego użycia useEffect, wykrywając 9 antywzorców z tekstu You Might Not Need an Effect.
  • 100react-useeffect
    Stosuje dobre praktyki useEffect z oficjalnej dokumentacji React i uczy, kiedy Effect jest zbędny, oraz pokazuje lepsze alternatywy dla wartości pochodnych, pobierania danych i synchronizacji stanu.
  • 100refactor-react-effects
    Refaktoryzuje zbędne użycia useEffect w kodzie frontendu Langfuse: dodawanie i usuwanie efektów, inicjalizacja formularzy, synchronizacja stanu klienta i serwera oraz przenoszenie mutacji poza komponenty.
  • 100conventions-use-effect
    Pilnuje, żeby w apps/web nie używać bezpośrednio useEffect, tylko zatwierdzonych opakowań albo prostszych rozwiązań.
  • 100conventions-use-effect
    Wymusza zasady pisania i recenzji efektów React w apps/web, gdzie bezpośredni useEffect jest zakazany i trzeba użyć dozwolonych wrapperów.
  • 95fixing-react-antipatterns
    Sprawdza kod React pod kątem antywzorców: błędne useEffect, brak sprzątania, przestarzałe domknięcia i wycieki pamięci, z oceną.

Uwagi i zgłoszenia

Wiadomość trafi do Bartosza Sokolińskiego. Adres e-mail jest potrzebny tylko do odpowiedzi. Szczegóły w polityce prywatności.