Pular para o conteúdo
Skillpedia
Sites e telas (frontend)9,7 mil · #12213

no-use-effect

O que ela faz

Este guia afasta seu agente de um padrão comum do React que costuma causar bugs e renderizações extras. É para desenvolvedores que escrevem ou revisam componentes e hooks React.

Quando usar

  • ✓Quando seu agente cria novos componentes ou hooks React.
  • ✓Quando ele refatora uma chamada de useEffect já existente.
  • ✓Quando um pull request adiciona um useEffect que você quer revisar.

Link da skill

https://github.com/fastrepl/anarlog/blob/main/.agents/skills/no-use-effect/SKILL.md

Copie e cole na sua IA (Claude, ChatGPT ou Cursor) pedindo para seguir as instruções.

Como usar

O jeito mais fácil: copie a mensagem e cole na sua IA. Ela lê a skill e segue as instruções.

Mensagem pronta para colar

Use esta skill para me ajudar: https://github.com/fastrepl/anarlog/blob/main/.agents/skills/no-use-effect/SKILL.md Leia o arquivo SKILL.md desse link e siga as instruções dele na minha tarefa.
Quer que a sua IA encontre skills como esta sozinha?Instale o MCP grátis do Skillpedia: uma linha, e ela pesquisa entre 15.000+ skills antes de cada tarefa.Instalar em 1 minuto →

Exemplo do que pedir para a IA

“Revise este componente React e remova qualquer useEffect que não seja realmente necessário.”

5 skills novas por semana. 1 minuto de leitura.

Como funciona

A skill primeiro pergunta por que cada efeito existe e depois o substitui pelo padrão mais simples que servir. Entre eles estão calcular valores durante a renderização, usar uma biblioteca de dados para buscar informações, tratar ações do usuário em manipuladores de eventos e um hook específico para configurações realmente únicas na montagem.

Conteúdo técnico (SKILL.md original)

Texto original do autor, em inglês, direto do GitHub.

No useEffect

Never call useEffect directly unless the work is a true mount-only sync with an external system and no simpler pattern fits. Prefer a render-time computation, a query or mutation hook, an event handler, or a remount boundary instead.

Workflow

  1. Classify why the effect exists.
  2. Replace it with the narrowest pattern below.
  3. Verify with the project's normal lint, typecheck, and tests.

Replacement Patterns

1. Derive state, do not sync it

Replace useEffect(() => setX(derive(y)), [y]) with inline computation or the project's existing memoization conventions.

const filteredProducts = products.filter((product) => product.inStock);

Smell test: state only mirrors props or other state.

2. Use query or mutation libraries for async work

Replace fetch-in-effect code with the app's data layer.

const productQuery = useQuery({
  queryKey: ["product", productId],
  queryFn: () => fetchProduct(productId),
});

Smell test: the effect fetches, awaits, retries, cancels, or writes async results into local state.

3. Use event handlers for user actions

Do the work where the action happens instead of setting a flag and reacting later.

const handleLike = () => {
  postLike();
};

Smell test: state exists only to trigger an effect, then gets reset.

4. Use useMountEffect for mount-only external sync

Use this only for work that is naturally "set up on mount, clean up on unmount": DOM integration, subscriptions, third-party widgets, and stable singleton bindings.

If the project already has a useMountEffect, use it. If not, add a small wrapper:

import { useEffect } from "react";

export function useMountEffect(effect: () => void | (() => void)) {
  useEffect(effect, []);
}

Prefer changing component structure so the component only mounts once preconditions are satisfied.

Smell test: the effect is a one-time setup or teardown for something outside React.

5. Use key to reset component state

If a component should behave like a fresh instance when an ID or entity changes, remount it from the parent.

return <VideoPlayer key={videoId} videoId={videoId} />;

Smell test: the effect exists only to reset local state when props change.

Review Standard

Treat new direct useEffect usage as a bug by default. Ask which of the five patterns applies. Accept direct useEffect only with explicit justification that the code is a mount-only external sync and that useMountEffect is the intended escape hatch.

Structure React Code This Way

Order component logic like this:

  1. Hooks that read external state or data.
  2. Local state.
  3. Derived values computed during render.
  4. Event handlers.
  5. Early returns.
  6. Render output.

Do not introduce mirrored state just to make an effect possible.

Perguntas frequentes

Quando o useEffect ainda é permitido?

Apenas para uma sincronização real com um sistema externo que roda uma vez na montagem, e só quando nenhum padrão mais simples serve.

Ela muda o comportamento do meu app?

O objetivo é manter o comportamento igual, e o guia pede que você rode depois suas verificações normais de lint, tipos e testes.

O que é um valor derivado?

Um valor calculado a partir de outros valores durante a renderização, em vez de ser copiado para uma variável de estado separada.

Detalhes

Descrição original do autor

Avoid direct React `useEffect` usage when writing or reviewing React components and hooks. Use this skill when creating new React code, refactoring existing `useEffect` calls, reviewing PRs that introduce `useEffect`, or when an agent reaches for `useEffect` as a default. Replace effects with derived state, query or mutation libraries, event handlers, `useMountEffect` for mount-only external sync, or `key`-based remounts.

repo: fastrepl/anarlog

Popularidade

Estrelas no GitHub
9,7 mil
Posição no ranking
#12213
Licença
MIT
Atualizada em
01/11/2026

Essa skill é útil?

0

Entre para votar.

Comentários

  • …

Mais skills deste repositório

Skills parecidas