useToggle: Custom react hook for toggle
Mehul Lakhanpal
Posted on July 6, 2021
// 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;
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>
);
};
Thanks for reading 💙
Follow @codedrops.tech for more.
Instagram ● Twitter ● Facebook
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
💖 💪 🙅 🚩
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.