Hooks

Custom hooks & the rules of hooks

Extracting reusable logic, hook rules, and subscribing to external stores.

advanced Experienced

A custom hook is a use-prefixed function that composes other hooks to extract reusable stateful logic. Two components sharing a hook share the logic, never the state — each call is isolated.

A custom hook is a shared recipe: every kitchen follows the same steps but cooks its own separate dish.

Key concepts

1
The rules of hooks: only call hooks at the top level (never in conditions or loops) and only from React functions. This is what lets React associate hook state with call order.
rules of hooks
2
For subscribing to non-React state (browser APIs, external stores) use useSyncExternalStore, which is concurrent-safe and avoids tearing.
`useSyncExternalStore`useSyncExternalStore
3
Pitfall: conditionally calling a hook, which corrupts the call-order mapping. Interview angle: "how would you build useDebouncedValue?" — internal state + an effect with a timer and cleanup, returning the debounced value.
Pitfall:Interview angle:useDebouncedValue