In modern React development, custom hooks are one of the most powerful tools at our disposal. They allow you to encapsulate logic and reuse it across components without the need for higher-order components or render props.

In this post, we’ll walk through what custom hooks are, how to create one, and why they improve both developer experience (DX) and code maintainability.


🔍 What is a Custom Hook?

A custom hook is a function in React whose name starts with use and may call other hooks inside it. It follows the same rules as regular hooks (like useState, useEffect, etc.).

They're just JavaScript functions but enable logic reuse between components.


💡 Why Use Custom Hooks?

  • ✅ Reuse logic across components
  • ✅ Abstract complex logic into readable, maintainable units
  • ✅ Improve code readability and testability
  • ✅ Avoid prop drilling and messy state management

🛠️ Creating Your First Custom Hook

Let’s build a simple custom hook that tracks the window width and returns whether it’s mobile-sized or not.

📦 useIsMobile.ts

import { useState, useEffect } from 'react';

export function useIsMobile(breakpoint = 768): boolean {
  const [isMobile, setIsMobile] = useState(window.innerWidth < breakpoint);

  useEffect(() => {
    const handleResize = () => {
      setIsMobile(window.innerWidth < breakpoint);
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, [breakpoint]);

  return isMobile;
}

✅ Usage

import { useIsMobile } from './hooks/useIsMobile';

function Navbar() {
  const isMobile = useIsMobile();

  return (
    <nav>
      {isMobile ? <MobileMenu /> : <DesktopMenu />}
    nav>
  );
}

Boom! You’ve separated the logic from the component UI, making everything easier to test and manage.


⚙️ Composable Hooks

You can also build more complex hooks using composition:

function useAuth() {
  const user = useUser();
  const token = useToken();

  return {
    user,
    token,
    isLoggedIn: !!user,
  };
}

📚 Best Practices for Custom Hooks

  • ✅ Prefix the hook name with use
  • ✅ Keep it focused (single responsibility)
  • ✅ Reuse existing hooks inside
  • ✅ Make them composable if needed
  • ✅ Add TypeScript typings for better DX

🚀 Conclusion

Custom hooks are essential to building modern React apps. They empower teams to write cleaner, DRY, testable code and accelerate development workflows.

Whenever you find yourself repeating logic across components — ask yourself: Can this be a hook?