Lesson 18 — Custom Hooks in React (Create Reusable Logic)

Introduction 😊

So far, you’ve learned about powerful React hooks like:

  • useState
  • useEffect
  • useContext

But what if:

  • The same logic is repeated in multiple components?
  • You want to reuse logic, not UI?

This is where Custom Hooks come in ⚛️

In this lesson, you will learn:

  • What custom hooks are
  • Why custom hooks are needed
  • How to create a custom hook
  • Real-world examples
  • Best practices and common mistakes

Let’s begin 🚀


What Are Custom Hooks? 🤔

A custom hook is a JavaScript function that:

  • Uses one or more React hooks
  • Starts with the word use
  • Helps reuse logic across components

👉 In simple words:

Custom hooks let you extract and reuse logic, not UI.


Why Do We Need Custom Hooks? 🧠

Without custom hooks:

  • Logic gets duplicated ❌
  • Components become large and messy ❌
  • Maintenance becomes difficult ❌

Custom hooks help you:

  • Write clean code ✨
  • Follow DRY principle (Don’t Repeat Yourself)
  • Improve readability and reusability

Rules for Creating Custom Hooks 📌

Custom hooks follow the same rules as React hooks:

1️⃣ Name must start with use
2️⃣ Can call other hooks
3️⃣ Must be used inside function components or other hooks

Example name:

useFetch
useCounter
useAuth


Example 1: Simple Custom Hook (Counter) 🔢

Custom Hook

import { useState } from "react";

function useCounter(initialValue = 0) {
  const [count, setCount] = useState(initialValue);

  const increment = () => setCount(count + 1);
  const decrement = () => setCount(count - 1);

  return { count, increment, decrement };
}

export default useCounter;


Using Custom Hook in Component

import useCounter from "./useCounter";

function CounterComponent() {
  const { count, increment, decrement } = useCounter(5);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>+</button>
      <button onClick={decrement}>-</button>
    </div>
  );
}

👉 Same logic can now be reused anywhere ♻️


Example 2: Custom Hook for Input Handling ⌨️

Custom Hook

import { useState } from "react";

function useInput(initialValue) {
  const [value, setValue] = useState(initialValue);

  const onChange = (e) => setValue(e.target.value);

  return {
    value,
    onChange
  };
}

export default useInput;


Usage

function Form() {
  const name = useInput("");

  return (
    <input
      type="text"
      placeholder="Enter name"
      {...name}
    />
  );
}

👉 Very clean and reusable ✨


Example 3: Custom Hook with useEffect 🌐

Fetch Data Hook

import { useState, useEffect } from "react";

function useFetch(url) {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch(url)
      .then(res => res.json())
      .then(data => setData(data));
  }, [url]);

  return data;
}

export default useFetch;

Usage:

const users = useFetch("https://api.example.com/users");


When Should You Create a Custom Hook? 🤔

Create a custom hook when:

  • Logic is repeated
  • Multiple components share same behavior
  • Hooks logic becomes complex

Do NOT create custom hooks for:

  • Simple one-time logic
  • UI rendering

Custom Hooks vs Components ⚖️

Custom HooksComponents
Reuse logicReuse UI
No JSXReturn JSX
Start with useCapitalized name

Common Mistakes Beginners Make ❌

  • Forgetting use prefix
  • Returning JSX from hooks
  • Using hooks inside conditions
  • Overengineering simple logic

💡 Keep hooks simple and focused.


Conclusion 🎯

Custom hooks are a powerful React feature that help you write clean and reusable code.

Key takeaways:

  • Custom hooks reuse logic, not UI
  • They follow same rules as React hooks
  • Improve readability and maintainability
  • Essential for scalable React apps

👉 If you master custom hooks, your React code becomes professional-level 💙


Frequently Asked Questions (FAQs) ❓

Can custom hooks use other hooks?

Yes, that’s their main purpose.

Can a custom hook return JSX?

No. Hooks should return data and functions.

Are custom hooks mandatory?

No, but highly recommended for reusable logic.


What’s Next? 🚀

👉 In the next lesson, we will learn:

Lesson 19 — Rules of Hooks Explained
Understanding the rules you must follow while using hooks.

Leave a Comment