DEV Community

Mertcan KOÇER
Mertcan KOÇER

Posted on

Custom Hooks - useToggle()

Hello everyone,

Today I am here to explain you to another custom hook, useToggle. We will continue with this hook as the second step in our Custom Hook adventure. It is a pretty simple hook. 🙂

So what's the point of this hook?

As you know, sometimes there are only values that we toggle. For example, the best example of this is sidebar status, whether the sidebar is opened or closed.

We want to know the instant status of the sidebar, but instead of assigning a boolean value directly to it, we want to toggle it.

In these cases, the useToggle custom hook comes to our aid. If we implement this hook, we can use it in such situations very easily. Below you can see the file structure I prepared for this hook and the implementation.

File Structure

import React, { useCallback, useEffect, useState } from "react";

// Part 1
const useToggle = (initialState: boolean = false) => {
  // Part 2
  const [state, setState] = useState(initialState);

  // Part 3
  const toggle = useCallback(() => setState((state) => !state), []);

  // Part 4
  return [state, toggle] as const;
};

// Part 5
export default useToggle;
Enter fullscreen mode Exit fullscreen mode

Explanations

Part 1
We name our function using the use....() pattern and take the necessary arguments. The argument we receive here specifies the initial state of toggle status.

Part 2
We need to manage state internally in our hook. To do so, we used useState() hook.

Part 3
Here we create the function that will provide the toggle operation. In this way, the person who will use the function will be able to switch between values with this function.

In case of passing components down, we should prevent unnecessary function redefinition with pre-defined useCallback hook.

Part 4
Just like the return value of the useState function, we return our state and toggle function as an array.

If you're using typescript just like me, you're probably wondering about the as const expression.

Since Typescript uses the union structure in values that we return as an array, it is quite natural to get an error. That's why we avoid type inference by spelling as const. You can get detailed information about this subject by clicking this link.

Part 5
Exporting that hook as a default export.

Usage

We explained everything clearly. Now the rest is using this hook in our source code. Below is the example App.tsx file.

import React from "react";
import { useToggle } from "./hooks";

function App() {
  const [isSidebarOpen, toggleSidebar] = useToggle();

  return (
    <div>
      <button onClick={toggleSidebar}>
        {isSidebarOpen ? "Toggled" : "Click to Toggle"}
      </button>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)