Labs ICT
โญ Pro Login

Custom Hooks

Extracting reusable logic into your own hooks.

What are Custom Hooks?

Custom Hooks are the secret sauce of reusable logic in React. They're just regular JavaScript functions that follow a naming convention - they start with "use" and can call other Hooks inside them. The magic is that they let you extract component logic into reusable functions. Instead of copy-pasting the same useState and useEffect setup across multiple components, you wrap it in a custom Hook once and use it everywhere.

Think of custom Hooks like recipes. Once you've figured out how to make the perfect pancake batter, you write down the recipe. Next time, you just follow the recipe instead of reinventing it. Custom Hooks are your component recipes - they capture a specific behavior and let you apply it to any component that needs it.

Creating Your Own Hooks

Creating a custom Hook is as simple as writing a function that uses other Hooks. The only requirement is that the function name starts with "use". Inside, you can use useState, useEffect, useContext, or any other Hook. The custom Hook can return whatever makes sense for your use case - values, functions, or combinations of both.

function useWindowSize() {
  const [size, setSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight
  })
  useEffect(() => {
    const handleResize = () => {
      setSize({
        width: window.innerWidth,
        height: window.innerHeight
      })
    }
    window.addEventListener("resize", handleResize)
    return () => window.removeEventListener("resize", handleResize)
  }, [])
  return size
}
Try it Yourself โ†’

Naming Conventions

The naming convention isn't just for style - it's required. React's linting tools use the "use" prefix to check that you're following the Rules of Hooks. If a function doesn't start with "use", React won't know to check it for Hook rule violations. Always prefix your custom Hooks with "use" followed by a capital letter, like useAuth, useFetch, or useDebounce.

Keep your custom Hooks focused on a single concern. A Hook that handles authentication, fetches data, and manages a form is doing too much. Split it into smaller, focused Hooks that each handle one thing well. This makes them easier to understand, test, and reuse.

Reusable Logic Extraction

The real power of custom Hooks is extracting logic that's used in multiple places. Notice you're setting up the same useState and useEffect for window size in five different components? That's a custom Hook waiting to happen. Extract it once, use it everywhere, and your components become cleaner and more focused.

function Header() {
  const { width } = useWindowSize()
  return <h1>Window is {width}px wide</h1>
}
function Sidebar() {
  const { width } = useWindowSize()
  return width > 768 ? <FullSidebar /> : <MiniSidebar />
}
Try it Yourself โ†’

๐Ÿงช Quick Quiz

What is a custom hook?