DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for React - Hooks as Optional Parameters
Bruno Noriller
Bruno Noriller

Posted on • Originally published at Medium

React - Hooks as Optional Parameters

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

Top comments (2)

Collapse
 
jakecarpenter profile image
Jake Carpenter

Yuck.

I would much rather stub the hook. Either that or build smaller components that make more sense for strict β€œunit” testing.

Collapse
 
noriller profile image
Bruno Noriller Author

Hey... I agree with you. But it's... something.

Also, playing around with it, and I should made this explicit, it was a little of a TIL moment.

You check the parameters of WeirdComponent, you have hook and then hook2 taking hook as an argument for it's hook.
It works in this order, but if you change the order it stops working.

And this is JS for you =D

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.