// 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
Top comments (2)
Consider using
useCallback
While not strictly necessary, not doing so creates a new callback function every single time
useToggle
is evaluated (as does defining a callback in theonClick={() => ...}
props), which means every time a component receives the new callback function, it re-renders, even though nothing about the callback actually changed.Great. Thanks for the suggestion and the efforts to update the example :) :)