React - Hooks as Optional Parameters

Bruno Noriller - Sep 18 '22 - - Dev Community

You can put hooks as parameters, but should you? And why would you want to do that?


Here’s a Sandbox with me playing around:

https://codesandbox.io/s/hooks-as-params-1wt4bm

But basically, it’s like this:

function WeirdComponent({
    hook = useHook(),
    hook2 = useAnotherHook(hook),
}) {
    return (
        <div>
            <div>{hook}</div>
            <div>{hook2}</div>
        </div>
    )
}

function useHook(){
    return "hook!"
}

function useAnotherHook(value){
    return value || "default value"
}
Enter fullscreen mode Exit fullscreen mode

And this will work exactly as if you would add the hooks inside the component.


But why would you do it?

Back when I realized it was possible, I used it as a way to simplify unit testing of some components.

This let me just pass the values I wanted without having to mock the hook.

Another surprising thing you can do is to inject a different hook depending on whatever you want and change a component compartment changing only the hook.


Should you?

Probably not.

Maybe there’s some niche use of this, but whatever you can do this way, you can do it in another way.

(If you have an idea for a use case of doing this I would love to know about it.)


Cover Photo by Grant Durr on Unsplash

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .