1. Why Custom Hooks

As your React app grows, you notice a pattern: the same stateful logic appears in multiple components. Three different components all do the same fetch → loading → data → error dance. Two components both debounce user input. Four pages all interact with the cart.

You could copy-paste the logic, but that creates a maintenance nightmare. Change the fetch logic in one place? You now have to change it in four. This is where custom hooks come in.

🛒
UrbanCart Problem
Duplicated fetch logic everywhere

UrbanCart's ProductList, ProductDetail, FeaturedProducts, and SearchResults components all fetch data from an API. Each one has its own loading, data, and error state, its own useEffect, its own error handling. That's 60+ lines of identical logic scattered across 4 files. A custom useFetch hook collapses it all into a single reusable function.

Before vs After Custom Hooks
Before
Copy-paste logic in 4 components
→
After
useFetch() in one place, used in 4

A custom hook is simply a JavaScript function that calls other hooks. It can use useState, useEffect, useRef, useCallback — anything. It returns whatever data or functions consumers need. No magic, no new API — just a function with a special naming convention.

2. Naming Rule — Must Start with use

React has one strict naming rule for custom hooks: the function name must start with use. This is not just a convention — React's linter (ESLint rules of hooks plugin) relies on this prefix to enforce the rules of hooks.

naming.js Custom Hook Naming
Why this matters: If you name a function getCart instead of useCart, React won't warn you if you accidentally call it inside a loop or an if-statement. The use prefix signals to the linter that rules of hooks apply.
✅

Do: useProductData

Starts with use. React and ESLint know this is a hook and will enforce rules accordingly.

❌

Don't: getProductData

Doesn't start with use. If it calls hooks internally, the rules-of-hooks linter won't catch violations.

3. Rules of Hooks

Custom hooks follow the same two fundamental rules as built-in hooks:

  • Only call hooks at the top level — never inside loops, conditions, or nested functions. React relies on hook call order being consistent across renders.
  • Only call hooks inside React functions — inside a function component or another custom hook. Never in regular JavaScript functions, class components, or event handlers.
rules.jsx Rules of Hooks — Correct vs Incorrect
Important: Each component that calls a custom hook gets its own independent state. Two ProductCard components both calling useFetch do not share data — they each run their own separate fetch with their own loading, data, and error state. Hooks are about sharing logic, not state.

4. useFetch — Generic Data Fetching

The most universally useful custom hook. Every app that fetches data needs the same three pieces of state: loading (show a spinner), data (display results), error (show an error message). useFetch encapsulates all of this.

hooks/useFetch.js Generic Fetch Hook

Now any component that needs to fetch data can use it in three lines:

ProductList.jsx Using useFetch
Hook return value
useFetch('/api/products') → { data: null, loading: true, error: null } // fetching → { data: [...], loading: false, error: null } // success → { data: null, loading: false, error: "404" } // failure

5. useLocalStorage — Persist State

UrbanCart needs the cart to survive page refreshes. Regular useState is wiped when the page reloads. useLocalStorage is a drop-in replacement that persists state in the browser's localStorage.

hooks/useLocalStorage.js Persistent State Hook
Cart.jsx Cart survives page refresh
API compatibility: useLocalStorage has the exact same [value, setValue] return shape as useState. You can swap them with one word change — no other code needs to change.

6. useDebounce — Delay Processing

UrbanCart's search bar fires an API request on every keystroke. A user typing "wireless headphones" (18 characters) sends 18 requests. Most are wasted. useDebounce waits until the user stops typing before firing the request — typically 300–500ms of silence.

hooks/useDebounce.js Debounce Hook
SearchBar.jsx Search that waits for user to stop typing
What debounce does to keystrokes
User types: w → wi → wir → wire → wirel... query updates: every keystroke ✓ debouncedQuery updates: only after 500ms of silence API call fires: only 1 time ✓

7. useCart — Encapsulate Cart Operations

Cart logic is complex: add items, remove items, update quantities, calculate totals, check if an item is already in the cart. Spreading this logic across components creates inconsistency. useCart is the single source of truth for all cart operations.

hooks/useCart.js Cart Operations Hook
ProductCard.jsx + CartPage.jsx Using useCart in multiple components
Sharing state across components: Each component calling useCart() gets its own isolated state. To share cart state across ProductCard and CartPage, wrap useCart inside a Context provider. That way, all components read from the same cart — a pattern you'll see in real production codebases.

8. Try It Yourself — useFetch Hook

This editor demonstrates a complete useFetch hook fetching real product data from dummyjson.com. Watch the loading state appear first, then the product cards render as data arrives. You can modify the URL or add error handling.

Try It Yourself — useFetch in Action
Preview

9. Try It Yourself — useDebounce Hook

Type in the search box and watch the two values below it. The top one (query) updates instantly with every keystroke. The bottom one (debouncedQuery) only updates 500ms after you stop typing. The filtered product list reacts to the debounced value — not the raw input.

Try It Yourself — useDebounce Search
Preview

Quiz

Question 1 of 5
What naming convention must all custom hooks follow?
Question 2 of 5
What can a custom hook contain?
Question 3 of 5
What problem do custom hooks primarily solve?
Question 4 of 5
If ProductCard and CartSummary both call useCart(), do they share the same cart state?
Question 5 of 5
Where can you legally call a custom hook?
0
/ 5
Great job!

You completed the Custom Hooks quiz.

Next Lesson

React Performance & Best Practices →
You've mastered custom hooks! Next: memoization, lazy loading, and profiling React apps.
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

You just built reusable React hooks.
Now build a career that hooks into top companies.

Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.

Explore our AI-era courses →