https://github.com/icyjoseph/context-hook-provider
A pattern proposal to move away from connect using hooks
https://github.com/icyjoseph/context-hook-provider
react-context react-hooks react-redux redux redux-provider
Last synced: about 1 month ago
JSON representation
A pattern proposal to move away from connect using hooks
- Host: GitHub
- URL: https://github.com/icyjoseph/context-hook-provider
- Owner: icyJoseph
- License: mit
- Created: 2019-04-23T23:27:06.000Z (about 7 years ago)
- Default Branch: master
- Last Pushed: 2022-12-10T17:15:28.000Z (over 3 years ago)
- Last Synced: 2025-02-23T02:11:18.709Z (over 1 year ago)
- Topics: react-context, react-hooks, react-redux, redux, redux-provider
- Language: JavaScript
- Homepage: https://nondescript-ship.surge.sh/
- Size: 448 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 22
-
Metadata Files:
- Readme: README.md
- License: License.md
Awesome Lists containing this project
README
# 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](https://nondescript-ship.surge.sh/).
## Install
As usual:
```bash
yarn add context-hook-provider
```
or
```bash
npm install context-hook-provider
```
## Usage
As usual, we create a redux store and pass it to the Provider.
```jsx
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(
,
document.getElementById("root")
);
```
Where Provider is:
```jsx
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 (
{children}
);
}
```
Then we can easily consume the state. Say for example that ``, has a child called ``.
```jsx
import React, { useContext } from "react";
import { State } from "context-hook-provider";
export function Counter() {
const {
state: { count }
} = useContext(State);
return
{count};
}
```
Furthermore, you can make a hook on the `count`.
```jsx
import { useContext } from "react";
export function useCount() {
const { state } = useContext(State);
return state.count;
}
```
And re-do the Counter.
```jsx
import React from "react";
import useCount from "./";
export function Counter() {
const count = useCount();
return
{count};
}
```