DEV Community

Cover image for Custom React Hooks: useBoolean

Custom React Hooks: useBoolean

Ludal πŸš€ on October 05, 2021

React hooks initially allow you to "hook into" React state and lifecycle features, like we used to do with the componentDidMount or componentWillUn...
Collapse
 
drfrost profile image
Mike Eling • Edited

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

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

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 πŸš€

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

Collapse
 
fidaay profile image
fidaay

Why not just

setShowSpoil(!showSpoil);
Enter fullscreen mode Exit fullscreen mode

?

Collapse
 
iamludal profile image
Ludal πŸš€ • Edited

It is a good practice to use the "function" form since the new value depends on the previous statue value. In most cases, both solutions will work correctly, but it is possible to have some kind of desynchronization (and so unexpected behaviors) when using your version.

A few keys here (though it is not exactly the same question as you) : stackoverflow.com/questions/610542...

Collapse
 
fidaay profile image
fidaay

That "desynchronization" occurs because of states mutations are asynchronous, and it shouldn't be treated as a problem nor unexpected behavior.

Collapse
 
kraskaska profile image
Kraskaska

well yes but actually no

Collapse
 
freetimeplay profile image
freetimeplay • Edited


const updateValue = useRef({
toggle: () => setValue(oldValue => !oldValue),
on: () => setValue(true),
off: () => setValue(false)
})

Why do we need useRef here instead of just return each function separately ?

Collapse
 
iamludal profile image
Ludal πŸš€

The goal of useRef is to make sure that these functions are not recreated every time the useBoolean hook is called. Internally, it is nothing more that a function call, and this function could actually be called many times if your component renders a lot.

By using useRef, we reuse the functions we created earlier without recreating them, which should improve the performance (though I didn't run any benchmarks by myself, so the performance gain might be big or small, but it is still a good practice).

Depending on the size of your application, removing useRef and returning the functions directly might not have any impact at all (or might even be faster, who knows).

Hope this helps, don't hesitate if something was not clear. :)

Collapse
 
joeattardi profile image
Joe Attardi

I don't know if we need an abstraction over a boolean value?

Collapse
 
iamludal profile image
Ludal πŸš€

Thanks for your comment! Indeed, we probably don't need so much abstraction (though it can simplify the overall code in a way). This one was more for educational purposes to understand the logic behind creating custom hooks, in order to implement more complex ones. 😁

Collapse
 
oliverflint profile image
Oliver Flint • Edited

HI @ludal , Are you aware that fluentui already has this exact hook... npmjs.com/package/@fluentui/react-...

Collapse
 
iamludal profile image
Ludal πŸš€

Hi Oliver, I didn't know about Fluent UI, but I know that Chakra UI also has such a hook (more info here), as well as other packages I guess. πŸ™‚