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

Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.