@designbycosmic/cosmic-react-state-management
v0.0.3
Published
State management using React context and useReducer
Downloads
3
Readme
App State
This is a redux-like approach to state management using React's Context API and the useReducer hook. Basic understanding of these concepts is helpful.
Inspired by this blog post
State Management with React Hooks and Context API in 10 lines of code!
Basic Idea
We set up a context
provider that wraps the entire app. The value
of that context provider is the result of the useReducer
hook, which includes the current state, plus a dispatch
function for updating the state.
How to Use
- Set up your
initialState
andreducer
, and pass these to thecreateAppState
function.
// src/state.js
import { createAppState } from "cosmic-react-state-management";
// Redux-like switch statement reducer
const reducer = (state, action) => {
switch (action.type) {
case "changeTheme":
return {
...state,
color: action.newTheme,
};
default:
return state;
}
};
// An object with the initial app state
const initialState = {
theme: "light",
};
// After passing the reducer and initial state, `createAppState` returns a
// React Context provider, consumer, and hook for getting/setting the app state
export const { AppStateProvider, AppStateConsumer, useAppState } = createAppState(reducer, initialState);
export default {
AppStateProvider,
AppStateConsumer,
useAppState,
};
- Wrap the app in the AppStateProvider. To do this in Gatsby, we have to export a function named
wrapRootElement
ingatsby-browser.js
// gatsby-browser.js
import React from 'react';
import { AppStateProvider } from "./src/state";
export const wrapRootElement = ({ element }) => {
return (
<AppStateProvider>{element}</AppStateProvider>
);
}
- For Functional Components, use the
useAppState
hook.
// src/components/ThemeChanger.js
import React, { useContext } from "react";
import { useAppState } from "../state";
const ThemeChanger = () => {
const [{ theme }, dispatch] = useAppState();
const changeTheme = dispatch({
type: "changeTheme",
newTheme: theme === "light" ? "dark" : "light",
});
return (
<Button type="button" onPress={changeTheme}>Change Theme</button>
);
};
export default ThemeChanger;
- For Class-based Components, use the
AppStateConsumer
wrapper component.
// src/components/ThemeChangerClass.js
import { AppStateConsumer } from "../state";
class ThemeChangerClass extends React.Component {
constructor() {
super();
this.changeTheme = this.changeTheme.bind(this);
}
changeTheme({ theme }, dispatch) {
dispatch({
type: "changeTheme",
newTheme: theme === "light" ? "dark" : "light",
});
}
render() {
return (
<AppStateConsumer>
{([ state, dispatch ]) => {
return(
<button
type="button"
onClick={() => this.changeTheme(state, dispatch)}
>Change Theme</button>
);
}}
</AppStateConsumer>
);
}
}
export default ThemeChangerClass;
- Optionally define separate reducers for easier code management.
// combine the reducers and initialState into single objects before passing to `createAppState`
const reducer = {
theme: // theme reducer,
user: // user reducer, e.g., logged-in status,
nav: // nav reducer, e.g., mobile nav showing
}
const initialState = {
theme: // theme initial state,
user: // user initial state,
nav: // nav initial state,
}
export const { AppStateProvider, AppStateConsumer, useAppState } = createAppState(reducer, initialState);
- Optionally run "middleware" functions before changing state
// src/state.js
import { registerMiddleware } from "cosmic-react-state-management";
registerMiddleware({
actionType: "changeTheme",
func: ({ newTheme }) => {
// track theme changes in Google Analytics
ga.send("userChangedTheme", newTheme);
},
});
You'll typically want to call
registerMiddleware
from wherever you define your reducer.