This repo is derived from the following Medium Article.
npm i -S react-state-hook
yarn add react-state-hook
import { StateProvider } from 'react-state-hook'
const App = () => {
const initialState = {
theme: { primary: 'green' },
}
const reducer = (state, action) => {
switch (action.type) {
case 'changeTheme':
return {
...state,
theme: action.newTheme,
}
default:
return state
}
}
return (
<StateProvider initialState={initialState} reducer={reducer}>
// App content ...
</StateProvider>
)
}
import { useStateValue } from 'react-state-hook'
const ThemedButton = () => {
const [{ theme }, dispatch] = useStateValue()
return (
<Button
primaryColor={theme.primary}
onClick={() => dispatch({
type: 'changeTheme',
newTheme: { primary: 'blue'}
})}
>
Make me blue!
</Button>
)
}```
import React, { Component } from 'react'
import { StateContext } from 'react-state-hook'
class ThemedButton extends Component {
static contextType = StateContext
render() {
const [{ theme }, dispatch] = this.context;
return (
<Button
primaryColor={theme.primary}
onClick={() => dispatch({
type: 'changeTheme',
newTheme: { primary: 'blue'}
})}
>
Make me blue!
</Button>
)
}
}
import userReducer from './reducers/user'
import basketReducer from './reducers/basket'
const mainReducer = ({ user, basket }, action) => {
// middleware goes here, i.e calling analytics service, etc.
return {
user: userReducer(user, action),
basket: basketReducer(basket, action)
}
}