When to Write Your Own Custom React Hook

While you can use the built-in hooks provided by React, writing your own custom hooks can be a useful way to abstract specific logic and make it reusable across your application. In this post, we’ll explore the benefits of writing custom react hooks and how they can help you write more organized and maintainable code.

Why Write Custom Hooks?

One of the main benefits of custom react hooks is that they allow you to reuse code across your application. Instead of duplicating the same logic in multiple components, you can extract that logic into a custom hook and use it in any component that needs it. This will help you avoid code duplication, which can make your code more difficult to maintain and debug. It will also make it easier to organize your code.

Custom react hooks can also make it easier to test your code. Because hooks are just functions, you can easily test them in isolation from your components. This can make it easier to ensure that your hooks are working as expected and can help you catch bugs before they become a problem.

Let’s Write a Simple Toggle Hook

There are often times when you need to switch the status of your app between two states. Think of a collapsible sidebar. It has two states, open or closed. You can certainly utilize useState to handle the status of the sidebar and then write a handler function to toggle between open and close. What if you need to toggle between dark and light mode? What if you need to toggle states in multiple components?

Even though it is such a simple hook, when you need to use it in multiple places, it’ll simplify your code just writing it once. The hook needs to do four things: set the initial state, track the current state, set the state, and toggle the state.

import { useState } from "react";

export const useToggle = (initial) => {
  const [isToggled, setToggle] = useState(initial);
  const toggle = () => setToggle((prevState) => !prevState);

  // Return named properties
  return { isToggled, setToggle, toggle };

In this sample component, I am using buttons to toggle and set the state of value.

import { useToggle } from "./useToggle";

export default function ToggleComponent() {
    value and functions can be renamed
  const { isToggled: value, toggle: toggleValue, setToggle } = useToggle(false);

  return (
      <h2>Toggle Component Demo</h2>
          display: "flex",
          flexDirection: "column",
          gap: "10px",
          <strong>Current value:</strong> <code>{value.toString()}</code>
        <button onClick={toggleValue}>Toggle</button>
        <button onClick={() => setToggle(true)}>Set to True</button>
        <button onClick={() => setToggle(false)}>Set to False</button>

You can find a working demo of the hook here. You can also find the full source code on my Git Repo.