context-hook-provider

1.0.3 • Public • Published

context-hook-provider

A pattern proposal.

The aim is to stop using connect. Instead, we should useContext and create hooks that select from the redux store.

Demo here.

Install

As usual:

yarn add context-hook-provider

or

npm install context-hook-provider

Usage

As usual, we create a redux store and pass it to the Provider.

import React from "react";
import ReactDOM from "react-dom";
import { createStore } from "redux";
import { Provider } from "context-hook-provider";

// using createStore directly from redux
const store = createStore(reducer); // the regular redux store

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("root")
);

Where Provider is:

import React, { createContext, useState, useEffect } from "react";

// create a Context
export const State = createContext();

export function Provider({ store, children }) {
  const [state, updateState] = useState(store.getState());

  const listener = () => updateState(store.getState());

  useEffect(() => {
    const unsub = store.subscribe(listener);
    return () => unsub();
  }, []);

  return (
    <State.Provider value={{ state, dispatch: store.dispatch }}>
      {children}
    </State.Provider>
  );
}

Then we can easily consume the state. Say for example that <App>, has a child called <Counter>.

import React, { useContext } from "react";
import { State } from "context-hook-provider";

export function Counter() {
  const {
    state: { count }
  } = useContext(State);
  return <div>{count}</div>;
}

Furthermore, you can make a hook on the count.

import { useContext } from "react";

export function useCount() {
  const { state } = useContext(State);
  return state.count;
}

And re-do the Counter.

import React from "react";
import useCount from "./";

export function Counter() {
  const count = useCount();
  return <div>{count}</div>;
}

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 1.0.3
    3
    • latest

Version History

  • Version
    Downloads (Last 7 Days)
    • Published
  • 1.0.3
    3
  • 1.0.2
    0
  • 1.0.1
    0
  • 1.0.0
    0

Package Sidebar

Install

npm i context-hook-provider

Weekly Downloads

3

Version

1.0.3

License

MIT

Unpacked Size

9.85 kB

Total Files

7

Last publish

Collaborators

  • icyjoseph