React counter hook
Open this example in our interactive code editor to experiment with it.
Try the EditorTik, 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
initialValueparameter (defaults to0) and usesuseStateinternally to manage the counter state. - increment and decrement functions use the functional form of
setCountwith(prev) => prev + 1and(prev) => prev - 1to safely update state based on the previous value. - The hook returns an object with
count,increment, anddecrement, 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
useCounterhook 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
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.
Related Pills
Event handlers arguments in React
onClick, onChange, onBlur... We usually pass a reference to the function handler but how do we add more arguments instead of just the event itself?
React toggles hook
Having too many dialogs, modals, popups and state starts to become repetitive? Solution - write a custom hook.
React Dark Mode hook
We'll create useDarkMode hook to switch between light and dark themes.