0.1.0 • Published 5 years ago

with-custom-hook v0.1.0

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

Overview

React HOC that passes the output of a custom hook as props to a presentational component. The idea is that we can utilize hooks in an idiomatic way and still get reasonable separation of concerns between stateful logic and UI. This pattern allows us to easily inject the output of a custom hook into any component.

Installation

  yarn add with-custom-hook

Example Usage

  import withHook from 'with-custom-hook';

  // Our custom hook. The returned values will be passed as props to our wrapped Presentational Component
  function useCount(initialValue?: number) {
    const [count, setCount] = React.useState(initialValue || 0);

    const increment = React.useCallback(() => setCount(x => x + 1), []);
    const decrement = React.useCallback(() => setCount(x => x - 1), []);

    return { count, increment, decrement };
  }

  interface CounterProps {
    count: number;
    increment: () => void;
    decrement: () => void;
  }

  // presentational component - props => UI
  const Counter: React.FC<CounterProps> = ({ count, increment, decrement }) => (
    <>
      <button onClick={increment}>increment</button>
      <button onClick={decrement}>decrement</button>
      <div>Count: {count}</div>
    </>
  );

  // Wrap our Counter presentational component with our HOC
  const WrappedCounter = withCustomHook(useCount)(Counter);

  // You can pass the custom hook's params as props on the wrapped components

  <WrappedCounter initialValue={10}>
0.1.0

5 years ago

0.0.13

5 years ago

0.0.12

5 years ago

0.0.11

5 years ago

0.0.10

5 years ago

0.0.9

5 years ago

0.0.8

5 years ago

0.0.7

5 years ago

0.0.6

5 years ago

0.0.5

5 years ago

0.0.4

5 years ago

0.0.3

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago