useConditionalHook
Conditionally call react hooks. Finally!!!
Installation
To install @rtbjs/use-conditional-hook
, simply use npm or yarn:
npm install @rtbjs/use-conditional-hook
# or
yarn add @rtbjs/use-conditional-hook
Usage
- Example with react
useEffect
:
import { useEffect } from 'react';
import { useConditionalHook } from '@rtbjs/use-conditional-hook';
const App = () => {
const [value, setValue] = useState(0);
// Returns context that needs to be rendered
const { context } = useConditionalHook(
useEffect, // The hook to call
[
() => {
console.log('useEffect');
},
[],
], // Array of arguents
value > 0 // Condition for calling the hook
);
return (
<div>
<button onClick={() => setValue(value - 1)}>Decrement</button>
<button onClick={() => setValue(value + 1)}>Increment</button>
{context}
</div>
);
};
export { App };
- Example with react
@rtbjs/use-network-speed
that returns a value:
import { useNetworkSpeedTest } from '@rtbjs/use-network-speed';
import { useConditionalHook } from '@rtbjs/use-conditional-hook';
const App = () => {
const [value, setValue] = useState(0);
// Returns the return from the hook
const { context, result } = useConditionalHook(
useNetworkSpeedTest,
[],
value > 0
);
// Run the test
useEffect(() => {
if (res?.runTest) res.runTest();
}, [!!res?.runTest]);
console.log(res);
return (
<div>
<button onClick={() => setValue(value - 1)}>Decrement</button>
<button onClick={() => setValue(value + 1)}>Increment</button>
{context}
</div>
);
};
export { App };
Types
type useConditionalHook = {
hook: any,
args: Array<any>,
isRendered: boolean
};
Issues tracker
Please report any issues and feature requests to: issues tracker