1.0.0 • Published 4 months ago

@rtbjs/use-conditional-hook v1.0.0

Weekly downloads
-
License
-
Repository
github
Last release
4 months ago

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

  1. 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 };
  1. 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