Notorious Puppy Memes

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

    1.0.3 • Public • Published

    Reducer Context Hook

    CircleCI

    A function that provides hooks to manage state with useReducer and useContext.

    Usage

    Create

    Creates instance of Hooks and StoreContextProvider;

    import create from "reducer-context-hook";
     
    type State = { count: number };
     
    type Action = { type: "reset" | "increment" | "decrement" };
     
    export const {
      StoreContextProvider,
      useDispatch,
      useMappedDispatch,
      useMappedState
    } = create<State, Action>();

    StoreContextProvider

    Please wrap your App with StoreContextProvider and pass reducer and initial state as props.

    function reducer(state: State, action: Action): State {
      switch (action.type) {
        case "increment":
          return { count: state.count + 1 };
        case "decrement":
          return { count: state.count - 1 };
        case "reset":
          return { count: 0 };
        default:
          throw new Error();
      }
    }
     
    const initialState: State = {
      count: 0
    };
     
    function App() {
      return (
        <StoreContextProvider reducer={reducer} initialState={initialState}>
          <App />
        </StoreContextProvider>
      );
    }

    useDispatch

    Get dispatch.

    function Increment() {
      const dispatch = useDispatch();
      const increment = React.useCallback(
        () => dispatch({ type: "increment" }),
        []
      );
      return <button onClick={increment}>+</button>;
    }

    useMappedDispatch

    Get actions from action creators.

    function Decrement() {
      const { decrement } = useMappedDispatch(
        {
          decrement: () => {
            type"decrement";
          }
        },
        []
      );
      return <button onClick={decrement}>-</button>;
    }

    useMappedState

    Get state from the store with mapState function.

    function Counter() {
      const { count } = useMappedState(
        state => ({
          count: state.count
        }),
        []
      );
      return <p>{count}</p>;
    }

    Licence

    MIT

    Keywords

    none

    Install

    npm i reducer-context-hook

    DownloadsWeekly Downloads

    3

    Version

    1.0.3

    License

    MIT

    Unpacked Size

    439 kB

    Total Files

    20

    Last publish

    Collaborators

    • sosukesuzuki