a year ago2min read

useCounter hook using React.js.

useCounter Image

Before we get started, make sure you have the following prerequisites in place:

  • Basic knowledge of React.js and functional components.
  • A React.js development environment set up.

Getting Started

Let's begin by creating our useCounter hook. This custom hook will encapsulate the logic for managing a counter value. We'll define three essential functions: increment, decrement, and reset, along with the count state.

import { useState } from "react";

function useCounter(initialCount = 0) {
  const [count, setCount] = useState(initialCount);

  const increment = () => {
    setCount(count + 1);
  };

  const decrement = () => {
    setCount(count - 1);
  };

  const reset = () => {
    setCount(initialCount);
  };

  return { count, increment, decrement, reset };
}

export default useCounter;

How to Use the useCounter Hook

Now that we've created our useCounter hook, let's see how we can use it in a React component.

import React from "react";
import useCounter from "./useCounter"; // Import the custom hook

function Counter() {
  const counter = useCounter(0); // Initialize the hook with an initial count of 0

  return (
    <div>
      <p>Count: {counter.count}</p>
      <button onClick={counter.increment}>Increment</button>
      <button onClick={counter.decrement}>Decrement</button>
      <button onClick={counter.reset}>Reset</button>
    </div>
  );
}

export default Counter;

In this example, we import the useCounter hook and use it to manage the state of our counter in the Counter component. We can access the count value and the three functions—increment, decrement, and reset—to interact with the counter's state.

Conclusion

Creating custom hooks like useCounter allows us to encapsulate complex logic and state management in a reusable and organized way. With this knowledge, you can extend your custom hooks to handle various state management scenarios in your React applications.

Now that you've learned how to create a useCounter hook, you can explore other custom hooks to improve the maintainability and scalability of your React projects. Happy coding!