Skip to content

commandFrontendreact

Extract Hook

Moves stateful logic out of a React component into a custom hook, keeps behavior identical and adds tests for the hook.

npx workspacetemplates add extract-hook --tool claude-code

Writes 1 file to .claude/commands/

.claude/commands/extract-hook.md14 lines · 1.2 KBFile
---
description: Moves stateful logic out of a React component into a custom hook, keeps behavior identical and adds tests for the hook.
argument-hint: "[component path and optionally the logic to extract]"
---

Extract a custom hook from the component: $ARGUMENTS

1. Read the component. Group the `useState`, `useReducer`, `useEffect`, `useMemo` and `useCallback` calls by purpose. Pick the group that has no JSX dependency, or the one named in the arguments.
2. Name the hook `use` plus what it manages (`useDebouncedSearch`, not `useLogic`). Place it next to the component or in the project's hooks folder, following existing files.
3. Move the code unchanged first. Return only what the component needs, as an object for more than two values. Pass inputs as parameters; do not read from outer scope.
4. Preserve effect cleanup and dependency arrays exactly. Run the exhaustive-deps lint rule and fix real warnings.
5. Write tests with `renderHook` (Testing Library) covering the initial state, one update and cleanup on unmount.

Run the component's existing tests, the new hook tests and the type check. Report the hook's signature and any behavior you suspect was already buggy but left alone.

What it does

Components that mix data fetching, state, effects and markup are hard to read and harder to test. This command picks out the logic that belongs together and moves it into a hook with a clear name and a small return value.

Rendering stays unchanged, and the hook gets its own tests, so the refactor can be checked rather than trusted.

Example

you › /extract-hook src/components/SearchBox.tsx the debounced query and results fetch

agent › Created src/hooks/useDebouncedSearch.ts: (query, delay) => { results, loading, error }. SearchBox now only renders.
Added useDebouncedSearch.test.ts with fake timers (3 tests). Existing SearchBox tests, tsc and eslint pass. Note: the old code never aborted stale requests; flagged, not changed.

Questions

Does behavior change?
It should not. The code is moved first with dependencies and cleanup intact, and the existing component tests must still pass.
Will it fix bugs it notices?
It reports them but leaves them alone, so the refactor stays easy to review.
  • A11y Check

    CommandFrontend

    Free
  • Add Form Validation

    CommandFrontend

    Free
  • Add Loading States

    CommandFrontend

    Free
  • Check Responsive

    CommandFrontend

    Free