July 6, 2021 06:05 pm GMT
Original Link: https://dev.to/318097/usetoggle-custom-react-hook-for-toggle-3g7
useToggle: Custom react hook for toggle
// File: useToggle.jsimport { 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
Original Link: https://dev.to/318097/usetoggle-custom-react-hook-for-toggle-3g7
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To