context-hook
    TypeScript icon, indicating that this package has built-in type declarations

    1.0.10 • Public • Published

    React Context Hook Builder

    Version Bundled size Coverage badge gree Typed Codebase MIT License

    Simple util that resolves common cases with react Context API.

    Util generates provider and hook dynamically from passed name.

    Installation

    npm install context-hook
    
    yarn add context-hook
    

    Usage

    Create context

    /* 
     * useCounter.ts
     */
    import { useState } from 'react';
    import { createContextHook } from 'context-hook';
    
    type Props = {
      defaultCount: number;
    }
    
    // Or you can create without props
    const useCounterLocal = (props: Props) => {
      const [count, setCount] = useState(payload.defaultCount);
    
      const increment = () => setCount((prev) => ++prev);
      const decrement = () => setCount((prev) => --prev);
    
      return [count, increment, decrement];
    };
    
    export const { CounterProvider, useCounter } = createContextHook('Counter', useCounterLocal) ;

    Connect to UI

    /* 
     * SomeUi.tsx
     */
    import { useCounter } from './useCounter';
    import { SomeUiComponent } from './SomeUiComponent';
    
    const SomeUi: React.VFC = () => {
      return (
        <CounterProvider defaultCount={2}>
          <SomeUiComponent />
        </CounterProvider>
      );
    };

    Use

    /* 
     * SomeUiComponent.tsx
     */
    import { useCounter } from './useCounter';
    
    export const SomeUiComponent: React.VFC = () => {
      const [count, increment, decrement] = useCounter();
    
      // - Count: 2 +
      return (
        <div>
          <button onClick={increment}>-</button>
          <p>Count: {count}</p>
          <button onClick={decrement}>+</button>
        </div>
      );
    };

    Install

    npm i context-hook

    DownloadsWeekly Downloads

    8

    Version

    1.0.10

    License

    MIT

    Unpacked Size

    19 kB

    Total Files

    17

    Last publish

    Collaborators

    • jefoce