DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk2 min

Understanding Custom Hooks in React with a Simple Counter Example

A custom Hook packages reusable component behavior. See how useCounter combines state with an interval, cleans it up, and returns a count for rendering.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A React custom Hook is a JavaScript function whose name starts with use and that can call other Hooks. It lets components reuse behavior—such as keeping a counter and advancing it on an interval—without putting all that logic in each component. Each call gets its own state; a custom Hook shares logic, not a shared state value.

What a custom Hook does

React describes custom Hooks as a way to share logic between components. A Hook such as useCounter can hold state and coordinate an Effect, while the component that calls it decides how to display the result. The React guide to reusing logic with custom Hooks demonstrates this idea with a counter.

The use prefix is meaningful: it identifies the function as a Hook, so it follows the Rules of Hooks and can call built-in or other custom Hooks. A clear, behavior-specific name also tells callers what the logic is for.

Extract a counter into useCounter

This example keeps a count in state, increments it once per second, and returns the count for rendering:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { useEffect, useState } from 'react';

export function useCounter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const id = setInterval(() => {
      setCount(c => c + 1);
    }, 1000);
    return () => clearInterval(id);
  }, []);

  return count;
}

export default function Counter() {
  const count = useCounter();
  return <h1>Seconds passed: {count}</h1>;
}

How the pieces work

  • useState(0) gives this Hook call a count initialized to zero.
  • useEffect starts an interval after the component is set up. The interval calls setCount(c => c + 1), a functional update that calculates the next value from the previous value.
  • The Effect returns cleanup that clears the interval when the component using the Hook is removed.
  • useCounter returns the current count; Counter handles presentation.

The empty dependency array means this Effect does not depend on changing reactive values from the component. For guidance on Effects and their setup and cleanup behavior, see React’s useEffect reference.

Custom Hook state is not shared automatically

If two components each call useCounter(), each call has its own independent count and interval. Reusing the Hook reuses the behavior, not the state instance. When components need to reflect one coordinated value, put that state in their closest common parent and pass it to them through props. React explains this approach in its guide to sharing state between components.

Call Hooks only at the top level

Call useCounter at the top level of a function component or another custom Hook. Do not call it conditionally, in a loop, in a nested function, or inside an event handler. The same rule applies to built-in Hooks such as useState and useEffect. See React’s Rules of Hooks guidance.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose a focused name and responsibility

Name a custom Hook for the concrete behavior it provides: React gives examples such as useData, useChatRoom, and useMediaQuery. Keep its API focused enough that a caller can understand what it does.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Avoid generic wrappers such as useMount that merely hide an Effect behind a lifecycle-sounding name. Such a wrapper can obscure which reactive values an Effect uses and make dependency mistakes harder for the Hooks linter to flag. When the behavior is synchronization with an external system, a focused Hook such as useChatRoom can make that purpose explicit.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.