DEV Community

Discussion on: Custom React Hooks: useBoolean

Collapse
meikatz profile image
Gregor Mitzka • Edited on

Or you just could use useMemo() for this, much easier:

const updateValue = useMemo(() => ({
  toggle: () => setValue(oldValue => !oldValue),
  on: () => setValue(true),
  off: () => setValue(false),
}), [ setValue ]);
Enter fullscreen mode Exit fullscreen mode
Collapse
link2twenty profile image
Andrew Bone • Edited on

You don't need setValue as a dep (because it's part of useState). I'd probably say useRef is better but you'd do it similarly to how you have.

const [value, setValue] = useState(initialValue)
const updateValue = useRef({
  toggle: () => setValue(oldValue => !oldValue),
  on: () => setValue(true),
  off: () => setValue(false),
});

return [value, updateValue.current]
Enter fullscreen mode Exit fullscreen mode

That being said I generally just use useState without any Boolean hook.

Thread Thread
iamludal profile image
Ludal 🚀 Author

You're right, I think useRef makes sense in this case and the way you used it. Thanks for pointing that out.