Extracting Reusable Business Logic into Custom Hooks
Extracting Reusable Business Logic into Custom Hooks
1. What Are Custom Hooks?
In early React, sharing stateful logic between components required complex patterns like Higher-Order Components (HOCs) or Render Props.
A Custom Hook is simply a JavaScript function whose name starts with use and that can call other React hooks (useState, useEffect, useRef, etc.).
Custom hooks allow you to extract component logic into reusable functions:
- Components focus purely on presentation and user interface.
- Custom hooks encapsulate state, network requests, and business rules.
2. The Naming Convention Rule
A custom hook must start with the lowercase word use (e.g., useAuth, useWindowSize, useFetch):
- React's ESLint plugin uses this naming prefix to automatically enforce the Rules of Hooks inside your custom function (ensuring hooks aren't called conditionally or in loops).
- If you omit the
useprefix, React will treat it as a standard function and will not warn you when hook violations occur.
3. Extracting a Window Dimensions Hook
Consider how multiple components (carousels, responsive charts, navigation drawers) need to know the browser's viewport width:
Without Custom Hook:
Every component duplicates 15 lines of useState, useEffect, and resize event listeners.
With Custom Hook (useWindowSize):
Clean Consumer Component:
4. Do Components Using the Same Custom Hook Share State?
*No! Custom Hooks share stateful logic, NOT state itself!*
Each call to a custom hook creates a completely independent container of state. If Component A and Component B both call useWindowSize(), each component has its own private windowSize state in React's Fiber tree. (If you want components to share the exact same state instance, combine the custom hook with React Context).
Practice Quiz
useState and useEffect?Building Practical Custom Hooks (useLocalStorage, useDebounce)
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.