React Custom Hooks
🧩 React Custom Hooks
Custom Hooks are JavaScript functions that start with use and allow you to reuse stateful logic across multiple components.
They let you extract common logic from components into reusable functions, keeping your code clean and organized.
🧠 Why Custom Hooks?
In React, multiple components often need similar logic, e.g.:
-
Fetching API data
-
Handling form input
-
Timer/interval logic
-
Local storage management
Instead of duplicating code in every component, we create a Custom Hook.
🛠 Syntax
-
Must start with
use(so React can track Hook calls) -
Can use other hooks (
useState,useEffect, etc.) inside
🧪 Example 1: Custom Hook for Window Width
Using the Custom Hook
✅ Logic is reusable and clean.
🧪 Example 2: Custom Hook for Form Input
Using the Custom Hook
✅ Multiple inputs handled without duplicating logic.
🧪 Example 3: Custom Hook for Fetching Data
Using the Custom Hook
✅ Reusable logic for any API.
🎯 Rules for Custom Hooks
-
Must start with
use -
Can call other hooks (
useState,useEffect,useReducer, etc.) -
Must follow Hooks rules (top-level calls, no loops/conditions)
-
Can return any type: value, object, array, or function
🔹 Benefits
| Benefit | Description |
|---|---|
| Reusable logic | Write once, use anywhere |
| Cleaner code | Reduces duplication |
| Composable | Combine multiple hooks |
| Encapsulates side-effects | Makes components simpler |
🎉 Summary
-
Custom Hooks extract and reuse logic
-
Can manage state, effects, timers, API calls
-
Keeps components clean and readable
-
Essential for modern React apps
