react-state-hook
v1.1.2
Published
A React hook for global state management
Downloads
5
Maintainers
Readme
React Flux Hook
This repo is derived from the following Medium Article.
Installation
npm
npm i -S react-state-hook
yarn
yarn add react-state-hook
Usage
Enhance Your App with Global State
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>
)
}
Then Use and Update the State Inside Your App
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>
)
}```
For Class Componnets
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>
)
}
}
Combining Reducers
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)
}
}