useToggle: Custom react hook for toggle

ml318097

Mehul Lakhanpal

Posted on July 6, 2021

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

💖 💪 🙅 🚩
ml318097
Mehul Lakhanpal

Posted on July 6, 2021

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

Sign up to receive the latest update from our blog.

Related