0
0
ReactConceptBeginner · 3 min read

What is a Custom Hook in React: Simple Explanation and Example

A custom hook in React is a reusable function that lets you share logic between components using React hooks like useState or useEffect. It helps keep your code clean by extracting common behavior into a single place.
⚙️

How It Works

Think of a custom hook as a recipe you write once and use in many dishes. In React, it is a function that starts with use and can call other hooks inside it. This function bundles together some logic that you want to reuse across different components.

For example, if multiple components need to track window size or fetch data, you can write that logic once in a custom hook. Then, any component can use that hook to get the same behavior without repeating code. This keeps your app organized and easier to maintain.

💻

Example

This example shows a custom hook that tracks the current window width. Any component can use it to get the window size and update when it changes.

jsx
import { useState, useEffect } from 'react';

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    function handleResize() {
      setWidth(window.innerWidth);
    }
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return width;
}

export default function WindowWidthDisplay() {
  const width = useWindowWidth();
  return <div>Window width is: {width}px</div>;
}
Output
Window width is: 1024px (or current window width in pixels)
🎯

When to Use

Use custom hooks when you have logic that needs to be shared between multiple components. This could be data fetching, form handling, animation, or any stateful behavior.

For example, if several parts of your app need to track user input or listen to browser events, a custom hook lets you write that logic once and keep components simple. It also makes testing easier because you can test the hook separately.

Key Points

  • Custom hooks start with use and can call other hooks.
  • They help reuse stateful logic across components.
  • They keep components cleaner and more focused on UI.
  • Custom hooks can return any value, like state, functions, or objects.
  • They follow the same rules as React hooks.

Key Takeaways

Custom hooks let you reuse React hook logic across components easily.
They are functions starting with 'use' that can call other hooks inside.
Use them to keep your components clean and share behavior like data fetching or event handling.
Custom hooks follow React's rules and can return any useful data or functions.
They improve code organization and make testing logic simpler.