snippet
useToggle
snippet
useToggle
Last updated December 3rd, 2022
Have you ever built features that require you to implement some sort of toggle? Whether it be an expanded or collapsed navigation menu, or revealing more content based on the state of a button in your UI, it's useful to switch between a true and false value to show and hide certain elements.
Naturally this logic is implemented directly in the same component that it's being used but this can lead you to rewrite the same logic multiple times if you have this same feature in multiple components. Above is a handy little react hook that you can place into your appplication but have the logic that does the switching of state abstracted away into it's own function.
useToggle
is almost exactly like useState
, however, this hook only takes and returns boolean values.
import { useState, useCallback } from "react";
const useToggle = (initialValue = false) => {
const [toggle, setToggle] = useState(initialValue);
const setterFunction = useCallback(() => {
return setToggle((prev) => !prev);
}, []);
return [toggle, setterFunction];
};
import useToggle from "./useToggle";
const App = () => {
const [openNav, setOpenNav] = useToggle();
return (
<>
{openNav ? "I'm an expanded nav menu" : "I'm a collapsed navMenu"}
<button onClick={setOpenNav}>Press me</button>
</>
);
};