Skip to main content
This page provides complete, working examples of custom React hooks from the 30 Seconds of Code collection. Each example includes the hook implementation and a practical usage demo.

Timing Hooks

useInterval - Declarative Intervals

Wrapping setInterval() in a React hook requires careful handling of closures and cleanup. Here’s a complete implementation:

useTimeout - Declarative Timeouts

Similar to useInterval, but for one-time delayed execution:
The implementation is nearly identical to useInterval, with the key difference being setTimeout vs setInterval.

useEffectOnce - Conditional One-Time Effects

Run a callback at most once when a condition becomes true:

Network Hooks

useFetch - Declarative Data Fetching

Fetch data with proper state management and abort controller support:

Event Hooks

useClickOutside - Outside Click Detection

Detect clicks outside an element - essential for dropdowns, modals, and popovers:

useClickInside - Inside Click Detection

Complement to useClickOutside for detecting clicks within an element:
Use useClickInside when you need to handle clicks on multiple children without adding individual onClick handlers to each.

Observer Hooks

useMutationObserver - DOM Change Detection

Watch for changes in the DOM tree using the MutationObserver API:

Lifecycle Hooks

Replicate Class Component Lifecycle

If you’re transitioning from class components, these hooks replicate lifecycle methods:

Key Patterns

useRef for Mutable Values

Use useRef when you need values that persist across renders but don’t trigger re-renders when changed.

Cleanup Functions

Always return cleanup functions from effects that add event listeners or create subscriptions.

Dependency Arrays

Include all values from component scope that are used in the effect to avoid stale closures.

Abort Controllers

Use AbortController for network requests to prevent memory leaks and race conditions.

Next Steps

1

Learn Components

See how these hooks are used in React Components.
2

Testing Hooks

Learn how to test custom hooks in the Testing Guide.