A custom hook is a function that starts with use and can call other hooks. It lets you extract reusable stateful logic.
Example
function useToggle(initial = false) {
const [value, setValue] = useState(initial);
const toggle = () => setValue(v => !v);
return [value, toggle];
}
// Usage
function App() {
const [isOn, toggle] = useToggle(false);
return <button onClick={toggle}>{isOn ? 'ON' : 'OFF'}</button>;
}
Your Task
-
Create a custom hook called useCounter that:
- Accepts an
initialValue parameter (default: 0)
- Returns an object:
{ count, increment, decrement, reset }
increment adds 1, decrement subtracts 1, reset goes back to initial
-
Use useCounter in TWO separate components:
CounterA: uses useCounter(0), renders in a div with id "counter-a"
CounterB: uses useCounter(10), renders in a div with id "counter-b"
- Each should display the count in a
<span className="count"> and have increment/decrement buttons
-
Crucially, each counter should work independently — clicking one doesn't affect the other.