DEV Community

Mehul Lakhanpal
Mehul Lakhanpal

Posted on • Originally published at codedrops.tech

useToggle: Custom react hook for toggle

// File: useToggle.js
import { useState } from "react";

const useToggle = (initialState = false) => {
  const [visible, setVisibility] = useState(initialState);

  const toggle = () => setVisibility((prev) => !prev);

  const setToggleStatus = (value) => setVisibility(Boolean(value));

  return [visible, toggle, setToggleStatus];
};

export default useToggle;
Enter fullscreen mode Exit fullscreen mode
import { useToggle } from "./useToggle";

const App = () => {
  const [visible, toggleVisibility, setVisibility] = useToggle(false);

  return (
    <div>
      <div>
        <button onClick={() => toggleVisibility()}>Toggle</button>
        <button onClick={() => setVisibility(false)}>Hide</button>
      </div>

      <div>{visible ? "Hello" : "Hidden content"}</div>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Thanks for reading 💙

Follow @codedrops.tech for more.

InstagramTwitterFacebook

Micro-Learning ● Web Development ● Javascript ● MERN stack

codedrops.tech


Projects

File Ops - A VS Code extension to easily tag/alias files & quick switch between files

Top comments (2)

Collapse
 
moresaltmorelemon profile image
Ezra Schwepker • Edited

Consider using useCallback

const toggle = useCallback(() => setVisibility((prev) => !prev), []);

return [visible, toggle, setVisibility];
Enter fullscreen mode Exit fullscreen mode
import { useCallback } from 'react';
import { useToggle } from "./useToggle";

const App = () => {
  const [visible, toggleVisibility, setVisibility] = useToggle(false);
  const hide = useCallback(() => setVisibility(false), []);

  return (
    <div>
      <div>
        <button onClick={toggleVisibility}>Toggle</button>
        <button onClick={hide}>Hide</button>
      </div>

      <div>{visible ? "Hello" : "Hidden content"}</div>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

While not strictly necessary, not doing so creates a new callback function every single time useToggle is evaluated (as does defining a callback in the onClick={() => ...} props), which means every time a component receives the new callback function, it re-renders, even though nothing about the callback actually changed.

Collapse
 
ml318097 profile image
Mehul Lakhanpal

Great. Thanks for the suggestion and the efforts to update the example :) :)