Custom Hooks
Subject: React
๐ What Are Custom Hooks?
A Custom Hook is a JavaScript function that starts with use and calls other hooks (like useState, useEffect, etc.).
They let you reuse stateful logic across components โ making your code cleaner, modular, and easier to maintain.
๐ฏ Why Use Custom Hooks?
Problem:
You keep duplicating the same state logic in multiple components.
โ Solution:
Extract that logic into a custom, reusable hook and use it wherever needed.
โ When to Use a Custom Hook
| Use Case | Reason to Use a Custom Hook |
|---|---|
| Repeated use of useEffect | Abstract side effects like data fetching |
| Shared useState logic | Reuse input/toggle logic |
| Complex logic (timers etc.) | Clean up component code |
| Working with APIs/storage | Encapsulation and reusability |
๐งฑ Custom Hook Rules
- Must start with
use - Can call other hooks (
useState,useEffect, etc.) - Cannot be called inside loops, conditions, or nested functions
- Must follow normal React Hook Rules
โ
Basic Custom Hook Example: useCounter
๐ง useCounter.js
๐งช Usage in Component
โ Custom Hook with useEffect: Fetch API
๐ง useFetch.js
๐งช Usage in Component
๐ง Benefits of Custom Hooks
| Benefit | Description |
|---|---|
| โป๏ธ Reusability | Use the same logic in multiple components |
| ๐งผ Cleaner Code | Keeps component logic short and focused |
| ๐งช Testability | Hooks are just functions โ easy to unit test |
| ๐ Composability | Custom hooks can call other custom hooks |
๐ฆ More Examples of Custom Hooks
| Custom Hook | Description |
|---|---|
useToggle() | Toggle a boolean value |
useLocalStorage() | Sync state with localStorage |
useDebounce() | Debounce fast-changing input values |
useWindowSize() | Track window width & height |
usePrevious() | Get the previous value of a prop/state |
๐ Summary Table
| Concept | Description |
|---|---|
| What is it? | A reusable function that uses other React Hooks |
| Naming | Must start with use |
| Return values | Typically returns an object with logic or state |
| Hook rules | Same as normal hooks โ no conditional or loop calls |
| Benefits | Cleaner, reusable, composable, testable code |
๐ง Real-Life Analogy
A custom hook is like a power tool ๐ ๏ธ โ once built, you can plug it in and reuse it in any project to speed up your workflow and reduce manual effort.
Advertisement Slot 1
Advertisement Slot 2