React  

How to Share Logic Between Components Using Custom Hooks in React

🔁 How Do I Share Logic Between Components with Hooks?

In traditional React (class components), shared logic often led to messy patterns like higher-order components (HOCs) and render props. But in the world of functional components, React gives us a better way:

🎉 Custom Hooks

✅ What Are Custom Hooks?

A custom hook is just a function that uses built-in React hooks (useState, useEffect, etc.) and can be reused across components.

By naming it with a use prefix (e.g. useAuth, useForm, useFetch), it follows React's Rules of Hooks.

🧠 Why Use Custom Hooks?

  • ♻️ Reusability: Share logic without duplicating code
  • Clean code: Keep components focused on UI
  • 🧪 Testability: Easier to unit test isolated logic
  • 💡 Separation of concerns: Abstract API calls, forms, timers, etc.

🧰 Real Example: useFetch Custom Hook

📦 Custom Hook (logic)

import { useState, useEffect } from "react";

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

    useEffect(() => {
        async function fetchData() {
            const res = await fetch(url);
            const json = await res.json();
            setData(json);
            setLoading(false);
        }
        fetchData();
    }, [url]);

    return { data, loading };
}

🧩 Component A

const Users = () => {
    const { data: users, loading } = useFetch('/api/users');
    return loading ? <p>Loading...</p> : <ul>{users.map(...)} </ul>;
};

🧩 Component B

const Posts = () => {
    const { data: posts, loading } = useFetch('/api/posts');
    return loading ? <p>Loading...</p> : <ul>{posts.map(...)} </ul>;
};

Boom 💥 — logic reused, no duplication, both components stay focused on UI.

🔐 Another Example: useAuth

function useAuth() {
    const [user, setUser] = useState(null);

    const login = (credentials) => {
        /* login logic */
    };

    const logout = () => {
        setUser(null);
    };

    return { user, login, logout };
}

Use this in any component that needs access to the user or auth actions!

📌 Best Practices for Custom Hooks

Tip Description
Prefix with use So React knows it's a hook
Keep them pure No JSX inside hooks
Return only what’s needed Make API simple and clear
Use other hooks inside them useState, useEffect, etc.
Don't call hooks conditionally Follow the Rules of Hooks

✅ Conclusion

Custom hooks are a powerful way to share logic between components while keeping your code clean, reusable, and testable.

  • 💡 Create a hook when you repeat logic across components
  • 🔄 Extract side effects, form logic, API calls, etc.
  • 🧱 Build a library of custom hooks as your project grows