TS

tsh-writing-hooks

Provides standards for building reusable, maintainable logic units like React hooks and Vue composables.

Install

mkdir -p .claude/skills/tsh-writing-hooks && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/10149" && unzip -o skill.zip -d .claude/skills/tsh-writing-hooks && rm skill.zip

Installs to .claude/skills/tsh-writing-hooks

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Custom hook and composable patterns — naming, composition, stable return shapes, lifecycle cleanup, and testing strategies. Use when writing reusable logic units (React hooks, Vue composables), refactoring logic into hooks, debugging hook behavior, or reviewing hook implementations.
283 chars✓ has a “when” triggerlonger than Claude Code's old 250-char listing cap (fine on current versions)
Intermediate

Key capabilities

  • Define hook contracts
  • Classify hook tiers
  • Implement lifecycle cleanup
  • Standardize return shapes

How it works

Provides patterns for single-responsibility composition, stable API surfaces, and mandatory resource cleanup in hooks.

Inputs & outputs

You give it
Logic unit requirements
You get back
Composable, testable hook implementation

When to use tsh-writing-hooks

  • Refactor business logic into reusable hooks
  • Standardize hook return shapes
  • Debug lifecycle-related memory leaks
  • Review hook composition patterns

About this skill

Writing Hooks

Provides patterns for writing composable, testable custom hooks with stable APIs, proper effect lifecycle management, and clear responsibility boundaries.

This skill uses "hook" to refer to any reusable, composable logic unit — React hooks, Vue composables, or equivalent framework abstractions. Adapt naming conventions and specific APIs to the project's framework.

<principles> <single-responsibility> Each hook does one thing. Compose complex behavior by calling multiple hooks, not by adding optional parameters to a single hook. A hook with 5+ configuration options is a sign it needs decomposition. </single-responsibility> <stable-api-surface> Prefer returning an object (rather than a tuple) once the hook returns more than 1–2 values, and keep references stable. Memoize callbacks and derived values using the framework's memoization primitives when consumers may pass them to memoized children. The hook's return shape is its public API — treat it as a contract. </stable-api-surface> <cleanup-everything> Every subscription, timer, event listener, or async operation created in an effect must have a corresponding cleanup. Leaked resources cause memory leaks and stale state bugs that are hard to diagnose. </cleanup-everything> </principles>

Hook Development Process

Use the checklist below and track progress:

Progress:
- [ ] Step 1: Define the hook's contract
- [ ] Step 2: Classify the hook tier
- [ ] Step 3: Implement with lifecycle discipline
- [ ] Step 4: Test the hook

Step 1: Define the hook's contract

Define the hook's public API before writing implementation code.

Naming: Follow the project's framework convention for reusable logic units. In React and Vue, the convention is use prefix + descriptive verb or noun. The name reflects behavior, not implementation details.

PatternExampleUse case
use + nounuseDebounce, useMediaQueryReturns a derived or observed value
use + verbuseToggle, useFetchReturns value + action(s)
use + domainuseAuth, useCartDomain-specific composition hook

Good: useLocalStorage — describes what it does. Bad: useBrowserEffect — describes how it works.

Inputs: Prefer a single options object when the hook accepts 3+ parameters. This makes the API extensible without breaking existing call sites.

// Prefer — single options object
const useDebounce = ({ value, delay, leading }: UseDebounceOptions) => {
  // ...
};

// Avoid — positional args are fragile past 2 params
const useDebounce = (value: string, delay: number, leading?: boolean) => {
  // ...
};

Outputs: Return an object with clear field names. Document what the hook returns and when it triggers effects.

interface UseAsyncReturn<T> {
  data: T | undefined;
  error: Error | null;
  isPending: boolean;
  refetch: () => void;
}

Step 2: Classify the hook tier

Determine where the hook fits in the dependency hierarchy. This classification constrains what a hook may depend on and prevents circular or inappropriate coupling.

TierNameScopeDependenciesExamples
AtomUI hooksLocal state, DOM events, media queries, keyboardNo remote data. No data-fetching libraries.useToggle, useMediaQuery, useKeyPress
MoleculeCoordination hooksCompose atom hooks with light coordination logicOther atom hooks only. No remote data.useFormField, usePagination
OrganismData hooksWrap data-fetching/mutation libraries. Domain logic.May call UI hooks internally. Interact with server cache.useUserProfile, useSearchResults

Rules:

  • Atom hooks must never import data-fetching or state management libraries.
  • Molecule hooks compose atoms — they do not call data hooks.
  • Organism hooks may call any tier but are the only tier that touches remote data.

Composability example — molecule hook composing atoms:

// Atom: single-purpose, no data fetching
const useDebounce = (value: string, delay: number) => {
  /* ... */
};
const useLocalStorage = <T>(key: string, initial: T) => {
  /* ... */
};

// Molecule: composes atoms into a higher-level behavior
const useDebouncedSearch = (storageKey: string) => {
  const { value, setValue } = useLocalStorage(storageKey, "");
  const debouncedValue = useDebounce(value, 300);
  return { query: value, setQuery: setValue, debouncedQuery: debouncedValue };
};

Step 3: Implement with lifecycle discipline

Follow these rules during implementation:

Call rules:

  • Call hooks/composables at the top level only — never inside conditions, loops, or nested functions.
  • Ensure all reactive dependencies are properly tracked — whether through explicit dependency arrays or automatic reactivity tracking, depending on the framework. Suppressing framework lint rules for dependency tracking is a last resort, not a shortcut.
  • Avoid object or array literals in dependency declarations — they create new identities every render/update cycle. Lift constants to module scope or memoize them.

Lifecycle cleanup — every effect that creates a resource must clean it up:

ResourceSetupRequired cleanup
TimersetTimeout(cb, delay)clearTimeout(id)
Event listeneraddEventListener(event, handler)removeEventListener(event, handler)
Async operationCancellable operation with AbortController signalcontroller.abort()
Subscriptionsource.subscribe(handler)subscription.unsubscribe()

The cleanup must execute when the hook unmounts or when dependencies change. See the framework reference for the exact cleanup syntax.

Error handling:

  • Don’t throw for expected runtime errors from the render/setup phase — surface those via the return value ({ error }).
  • It is acceptable to throw during render/setup for programmer errors (for example, a useX hook used outside its Provider) or when integrating with Error Boundaries / Suspense.
  • Catch async errors inside effects and store them in state.

Conditional execution:

  • Data hooks should support an enabled flag to prevent wasteful operations when preconditions are not met.
const useUserProfile = ({ userId, enabled = true }: Options) => {
  // Skip data fetching when disabled — delegate to data fetching library's enabled/skip option
  // Return idle state: { data: undefined, isPending: false, error: null }
};

Step 4: Test the hook

Use the framework's hook/composable testing utility. Structure tests around four areas:

  1. Initial state — Verify the hook returns the expected default values on first render.
  2. State transitions — Trigger actions and assert the return value updates correctly.
  3. Effect cleanup — Unmount the hook and verify all resources are released (timers cleared, listeners removed, subscriptions cancelled).
  4. Error states — Simulate failures and verify the hook surfaces errors via its return value.

For data hooks: wrap the test in required providers (query client, context providers) and mock network responses.

For timer-dependent hooks: use fake timers to control time progression without real delays.

it("cleans up the timer on unmount", () => {
  // Enable fake timers (syntax varies by test runner)
  // Render the hook using the framework's testing utility
  // Unmount
  // Advance all pending timers — verify no leaked side effects
  // Restore real timers after test
});

Return Shape Guidelines

Return typeWhenExample
Single valueHook computes one thinguseDebounce(value, delay)debouncedValue
ObjectMultiple related values or actions{ data, error, isPending, refetch }
Object (prefer over tuple)Readability and evolvability matter{ count, increment, decrement, reset }

Prefer objects over tuples for hooks returning more than one value. Objects are self-documenting, allow consumers to destructure only what they need, and evolve without breaking existing call sites.

Anti-Patterns

Anti-PatternInstead Do
Tuple return [value, setter] for complex hooksObject return { value, setValue, reset }
Effect with suppressed dependency trackingInclude all deps; restructure if cycle occurs
New object/array identity every renderMemoize or lift to module scope
Side effects in render phaseMove to lifecycle effect or event handler
Swallowing errors silentlyReturn { error } so consumer can handle
One mega-hook with 10 options

Content truncated.

When not to use it

  • Simple component-local logic
  • Non-reusable logic

Limitations

  • Requires framework-specific adaptation
  • Strict adherence to tier rules

How it compares

It enforces a tiered dependency hierarchy to prevent circular coupling, unlike generic hook writing approaches.

Compared to similar skills

tsh-writing-hooks side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
tsh-writing-hooks (this skill)03moNo flagsIntermediate
code-standards25moReviewBeginner
js-tosorted-immutable16moNo flagsBeginner
writing-react-effects13moNo flagsIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

Search skills

Search the agent skills registry