react Intermediate

React counter hook

React counter hook
React Counter Hook

Open this example in our interactive code editor to experiment with it.

Try the Editor

Tik, Tok, Tik, Tok

import { useState } from "react";

const useCounter = (initialValue = 0) => {
  const [count, setCount] = useState(initialValue);

  const increment = () => setCount((prev) => prev + 1);
  const decrement = () => setCount((prev) => prev - 1);

  return { count, increment, decrement };
};

export default useCounter;
import useCounter from "./useCounter";

export default function App() {
  const { count, increment, decrement } = useCounter(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
}

Summary

  • useCounter hook accepts an initialValue parameter (defaults to 0) and uses useState internally to manage the counter state.
  • increment and decrement functions use the functional form of setCount with (prev) => prev + 1 and (prev) => prev - 1 to safely update state based on the previous value.
  • The hook returns an object with count, increment, and decrement, making it easy to destructure and use in any component.
  • Custom hooks let you extract and reuse stateful logic across multiple components without duplicating code. The useCounter hook is a simple but practical example of this pattern.

Try this in our interactive code editor

Practice hands-on with our built-in code sandbox.

Open Code Editor
Adrian Bigaj
Adrian Bigaj

Creator of BigDevSoon

Full-stack developer and educator passionate about helping developers build real-world skills through hands-on projects. Creator of BigDevSoon, a vibe coding platform with 21 projects, 100 coding challenges, 40+ practice problems, and Merlin AI.