DEV Community

Discussion on: Custom React Hooks: useBoolean

Collapse
drfrost profile image
Mike Eling • Edited on

I suggest you memoize the updateValue API because now it's being recreated on every rerender (state change).

You can use a ref for that, let's say:

const [value, setValue] = useState(initialValue ?? false);
const updateApiRef = useRef(null); // null just for initialization.

if(updateApiRef.current === null)
{
   // This will initialize the API with a memoized object.
    updateApiRef.current = {
        toggle: () => setValue(oldValue => !oldValue),
        on: () => setValue(true),
        off: () => setValue(false),
    }
}
// At this point, updateApiRef.current is not equal to null anymore, before even returning it.
return [value, updateApiRef.current];
Enter fullscreen mode Exit fullscreen mode

I hope this makes sense, writing code on a phone is rly hard πŸ₯΅

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.