Skip to main content

What are Custom Hooks?

Custom hooks are JavaScript functions that use React’s built-in hooks to encapsulate and reuse stateful logic across multiple components. They follow the convention of starting with “use” and can call other hooks.

Benefits of Custom Hooks

Reusability

Extract common logic into reusable functions that can be shared across components

Separation of Concerns

Keep component logic separate from presentation code for better maintainability

Testability

Test complex logic independently from component rendering

Composition

Combine multiple hooks to create more powerful abstractions

Available Custom Hooks

This project includes three custom hooks that demonstrate different patterns and use cases:

useCounter

A simple hook for managing counter state with increment, decrement, and reset functionality.

useCounter

Manage counter state with built-in increment, decrement, and reset operations
Use cases:
  • Simple counting functionality
  • Stepper components
  • Quantity selectors
  • Demo of basic custom hook patterns

useGifs

A sophisticated hook for searching and caching GIF results from the Giphy API.

useGifs

Search GIFs with built-in caching and search history tracking
Use cases:
  • API data fetching and state management
  • Implementing client-side caching with useRef
  • Managing search history
  • Async operations in custom hooks

useWeather

A comprehensive hook for fetching weather data with geolocation, localStorage persistence, and auto-loading.

useWeather

Fetch weather data with automatic caching and state management
Use cases:
  • Complex async workflows with multiple API calls
  • Local storage integration
  • Auto-loading data on component mount
  • Advanced error handling patterns

Custom Hook Best Practices

Custom hooks must follow the naming convention useSomething to indicate they follow the Rules of Hooks.
  • Only call hooks at the top level (not inside loops, conditions, or nested functions)
  • Only call hooks from React functions (components or custom hooks)
Return an object with named properties for better clarity, or an array for destructuring flexibility like useState.
Use useEffect for side effects and useCallback for memoized functions to prevent unnecessary re-renders.
Add type definitions to your custom hooks for better developer experience and catch errors early.

Next Steps

Explore each custom hook to understand different patterns and techniques:

useCounter

useGifs

useWeather

Build docs developers (and LLMs) love