React Hooks for accessing state and dispatch from a store
# Yarn
yarn add context-hooks
# NPM
npm install --save context-hooks
// bootstrap your app
import { StoreContext, createStore } from 'context-hooks'
ReactDOM.render(
<StoreContext.Provider value={store}>
<App />
</StoreContext.Provider>,
document.getElementById('root'),
)
// individual components
import { useReducers, useConntect } from 'context-hooks'
const App = () => {
const state = useConntect((state) => ({
count: state.counter.count,
}))
const { counter } = useReducers()
return (
<Fragment>
Count: {count}<br />
<button onClick={() => counter.increase()}>increase count</button>
<button onClick={() => counter.decrease()}>decrease count</button>
</Fragment>
)
}
NOTE: React hooks require react
and react-dom
version 16.8.0
or higher.
// reducers
export default {
counter: {
initialState: {
count: 0,
},
increase = (state) => ({ count: state.count + 1 }),
decrease = (state) => ({ count: state.count - 1 }),
},
}
// bootstrap your app
import { StoreContext, createStore } from 'context-hooks'
import reducers from './reducers'
const store = createStore(reducers)
ReactDOM.render(
<StoreContext.Provider value={store}>
<App />
</StoreContext.Provider>,
document.getElementById('root'),
)
// individual components
import { useReducers, useConntect } from 'context-hooks'
const App = () => {
const state = useConntect((state) => ({
count: state.counter.count,
}))
const { counter } = useReducers()
return (
<Fragment>
Count: {count}<br />
<button onClick={() => counter.increase()}>increase count</button>
<button onClick={() => counter.decrease()}>decrease count</button>
</Fragment>
)
}