๐ 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