useCounter hook
React
JavaScript
Easy
Objective
Create a custom hook to handle counting, it should return the current count, plus functions to handle incrementing and decrementing the count
Requirements
The hook should be called
useCounter
The hook should take an initial value
If the user doesn't provide one, it should be 0
The hook should return
The current count
A function to increment the count by 1
A function to decrement the count by 1
The return values can either be an array or an object
The hook should be written in JavaScript
Solution
Here's how I would approach this, but keep in mind there might be other ways to solve this problem.
import React, { useState } from 'react';
function useCounter (initialValue = 0) {
const [count, setCount] = useState(initialValue);
function increment () {
setCount(count + 1);
}
function decrement () {
setCount(count - 1);
}
return {
count,
increment,
decrement,
};
}
export default useCounter;
// Usage
// const { count, increment, decrement } = useCounter();
Click to reveal