Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 18, 2022 10:15 pm GMT

React - Hooks as Optional Parameters

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

Heres a Sandbox with me playing around:

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

But basically, its 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"}

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 theres 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


Original Link: https://dev.to/noriller/hooks-as-optional-parameters-5e26

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To