imbhargav5 / rooks

Essential React custom hooks ⚓ to super charge your components!
https://rooks.vercel.app
MIT License
3.19k stars 216 forks source link

useEffectOnceWhen function declaration #1727

Closed ftreedom closed 10 months ago

ftreedom commented 1 year ago

Hi everyone,

I've encountered a strange behavior with useEffectOnceWhen today with a component like this:

const ExampleComponent = ({condition}: {condition?: boolean}) => {

.....

useEffectOnceWhen(() => {
    // do stuff
 }, condition)

.....
}

The condition was fired every time despite the fact that the component was rendered like this: <ExampleComponent /> After some debugging and taking a closer look at the code I've noticed that condition prop is optional, and the current type declaration on useEffectOnceWhen is not really helpful in this case.

This is the current type definition of useEffectOnceWhen: declare function useEffectOnceWhen(callback: () => void, when?: boolean): void;

I would suggest changing it like this: declare function useEffectOnceWhen(callback: () => void): void declare function useEffectOnceWhen(callback: () => void, when: boolean): void

This could be helpful to ensure that if a condition is passed, its value would be boolean.

I wanted to be sure that this could be an improvement for you all before opening a PR.

mrclay commented 1 year ago

Can you explain why passing an undefined variable to the hook is problematic? I think it’s idiomatic that functions should treat foo() and foo(undefinedVar) the same and both should be allowed by the type.

Users should be responsible for managing values they pass in rather than assuming every API is going to cast.

stale[bot] commented 10 months ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.