Skip to content

Instantly share code, notes, and snippets.

@rphansen91
Last active November 4, 2018 01:48
Show Gist options
  • Save rphansen91/6d330ad6380f09e2a022382e7ab425c9 to your computer and use it in GitHub Desktop.
Save rphansen91/6d330ad6380f09e2a022382e7ab425c9 to your computer and use it in GitHub Desktop.
React redux connect implementation using react hooks.
import React from 'react';
import useStore from './useStore';
import Todo from './Todo'
import { todoActions } from './actions';
export default () => {
const [
todos,
{ addTodo, rmTodo }
] = useStore(store => store.todos, todoActions)
return <div>{ todos.map((todo, i) => <Todo key={i} todo={todo} />) }</div>
}
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from './useStore';
import createStore from './store';
import App from './App';
ReactDOM.render(
<Provider store={createStore()}>
<App />
</Provider>,
document.getElementById('root')
);
import React, { useState, useContext, useEffect, createContext } from "react"
import { bindActionCreators } from "redux"
const context = createContext()
const isFn = (fn) => typeof fn === "function"
const mapStateFactory = (selector) => isFn(selector) ? selector : () => ({})
const mapDispatchFactory = (actions, dispatch) =>
isFn(actions)
? actions(dispatch)
: bindActionCreators(actions, dispatch)
export default function (mapState, mapDispatch) {
const { getState, dispatch, subscribe } = useContext(context).store
const mapStateEffect = mapStateFactory(mapState)
const actions = mapDispatchFactory(mapDispatch, dispatch)
const currentWorkingState = () => mapStateEffect(getState())
const [state, setState] = useState(currentWorkingState())
useEffect(() =>
subscribe(() => {
const newState = currentWorkingState()
if (state !== newState) {
setState(newState)
}
}), [])
return [state, actions]
}
export const Provider = ({ store, children }) => <context.Provider value={{ store }}>{children}</context.Provider>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment