useCounter
- React Native course
- Intermediate
- Lesson 9/116
- 5 min
Learn the useCounter custom hook.
What is useCounter?
useCounter is a custom hook that manages a counter. It holds a number with useState and returns increment and reset functions. You call it as const [count, increment, reset] = useCounter(0).
This hook collects repeated counter logic in one place. You can pass an amount to increment: increment(5) steps by five. Reset returns to the initial value with reset(). If many screens use a counter, useCounter keeps them consistent and short.
Using useCounter
In a component you write const [count, increment, reset] = useCounter(0). When buttons are pressed you call the matching function; count updates each time and the screen re-renders.
The initial value comes from the argument; different screens can pass different starts. You can also pass an argument to increment: increment(5) steps by five. This flexibility makes useCounter useful in real apps, especially shopping carts, scoreboards and games.
Practice Write useCounter
Write the useCounter custom hook. Hold a count with useState (initial value initial). The increment function adds count + n (n defaults to 1). The hook returns [count, increment].
Starter code
// Import useState
// Write the useCounter custom hook
// Start count state with initial
// increment adds n
// Return [count, increment]Sample solution
import { useState } from "react";
function useCounter(initial) {
const [count, setCount] = useState(initial);
const increment = (n = 1) => setCount(count + n);
return [count, increment];
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the useCounter parts
| Term | Meaning |
|---|---|
increment |
Raises the number |
reset |
Returns to start |
count |
Held number |
initial |
First value |
2 Complete the increment body
function useCounter(initial) {
const [count, setCount] = useState(initial);
const increment = (n = 1) => setCount(____);
return [count, increment];
}
function useCounter(initial) {
const [count, setCount] = useState(initial);
const increment = (n = 1) => setCount(count + n);
return [count, increment];
}
Explanation: count + n adds the given amount.
3 What does useCounter return?
const [count, increment] = useCounter(0);- The number and an increment function Correct answer
- Only the increment function
- Nothing
- Only the number
Explanation: useCounter returns the number and the increment function.