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

  1. The hook should be called useCounter

  2. The hook should take an initial value

    1. If the user doesn't provide one, it should be 0

  3. The hook should return

    1. The current count

    2. A function to increment the count by 1

    3. A function to decrement the count by 1

  4. The return values can either be an array or an object

  5. 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