A Simple Guide to Making a Custom React Hook

yashnirmal

Yash Nirmal

Posted on November 6, 2023

A Simple Guide to Making a Custom React Hook

Introduction

Today we'll work on creating a custom counter hook that encapsulates counter logic and allows us to build reusable and efficient components.

Our custom counter hook will provide functionalities to increase, decrease, and reset a counter value. Additionally, it will expose the current count value, allowing components to display it and interact with it effortlessly.

Image description

Code

1. useCounter.js

To begin our journey, let's create a new file in your favorite code editor and name it something like useCounter.js(you can name your hook anything just make sure to put 'use' in the beginning like useMyHook.js, useHookName, etc).

Now, let's implement our custom counter hook using the power of React's useState hook. Inside, write the following code

// useCounter.js

import { useState } from 'react';

export const useCounter = (value = 0) => {
  const [count, setCount] = useState(value);

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

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

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

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

Enter fullscreen mode Exit fullscreen mode

In this code snippet, we import the useState hook from React. Our useCounter custom hook accepts an optional value parameter, with a default value as 0

Inside the hook, we create a count state variable using useState, initialized with the value. We then define three functions: increment, decrement, and reset. These functions use the setCount function to update the count state variable.

The increment function increases the count value by 1, decrement decreases it by 1, and reset sets it back to the value.

Finally, our custom hook returns an object containing the count value, as well as the increment, decrement, and reset functions. By returning this object, we enable any component using our custom hook to access and control the counter's state easily.

2. Using our Custom Counter Hook

Now, let's see our custom counter hook in action! Create a new react component (I have named my component CounterComponent.js), and let's build a simple counter component that leverages the power of our custom hook.

import React from 'react';
import { useCounter } from 'path/to/useCounter';

export default function CounterComponent() {
  const { count, increment, decrement, reset } = useCounter();

  return (
    <div>
      <h2>Counter: {count}</h2>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
      <button onClick={reset}>Reset</button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

In this component, we import our custom hook useCounter and invoke it to initialize the count variable, as well as the increment, decrement, and reset functions.

We then render the current count value within a <h2> tag, and provide three buttons: "Increment," "Decrement," and "Reset." By associating the respective functions with the buttons' onClick event handlers, we allow users to interact with the counter and trigger the desired actions.

Conclusion

Woohoo! We have successfully built our first custom hook in React. Now you can effortlessly create numerous counters throughout your application without duplicating code or compromising maintainability.

Thanks for being till the end. Checkout my other blogs below👇

https://dev.to/yashnirmal

💖 💪 🙅 🚩
yashnirmal
Yash Nirmal

Posted on November 6, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related