React Ducks
Implement ducks in React following the redux pattern but using React Context.
Uses immer
to wrap reducers when creating, ensuring atomic state mutations.
Usage
Create the ducks for each slice of application logic.
export default createDuck({
name: "counter",
initialState: 0,
reducers: {
increment: (state) => state + 1,
},
actionMapping: { otherActionType: "increment" },
selectors: { current: (namespacedState) => namespacedState["counter"] },
});
Note: The current
selector is just an example. In an actual implementation it would be made redundant by $
which is created by default for all ducks to fetch the namespaced state.
counterDuck.selectors.$(state);
Create the root/global duck as a combination of all other ducks.
export default createRootDuck(counterDuck, otherDuck);
Create the global context.
export default createContext(
rootDuck.reducer,
rootDuck.initialState,
enhancer,
"ContextName",
useAsGlobalContext
);
Note: The enhancer
may be optionally specified to enhance the context with third-party capabilities such as middleware, time travel, persistence, etc. The only context enhancer that ships with Ducks is applyMiddleware.
Note: The useAsGlobalContext
i.e. global
option; allows for setting a default context that is used by the useDispatch
and useSelector
hooks when no Context
is supplied. This is useful when creating the context that will be used with the root provider.
Use the state and actions in your component.
export default function App(props) {
const { state, dispatch } = React.useContext(Context);
const count = counterDuck.selectors.$(state);
const increment = React.useCallback(
() => dispatch(counterDuck.actions.increment()),
[dispatch]
);
return (
<div>
Count: <span>{count}</span>
<button onClick={increment} />
</div>
);
}
Note: The use of React.useContext
can be replaced with a combination of useDispatch
and useSelector
hooks.
...
const count = useSelector(counterDuck.selectors.$, Context);
const increment = useDispatch(counterDuck.actions.increment, Context);
...
Note: This is equivalent to the class component described below.
export default class App extends React.PureComponent {
static contextType = Context;
render() {
const { state } = this.context;
return (
<div>
Count: <span>{counterDuck.selectors.$(state)}</span>
<button onClick={this.increment} />
</div>
);
}
increment = () => {
this.context.dispatch(counterDuck.actions.increment());
};
}
Wrap the application in the root provider to handle state changes.
const rootElement = document.getElementById("root");
const Provider = createRootProvider(Context);
ReactDOM.render(
<Provider>
<App />
</Provider>,
rootElement
);
Note: createRootProvider
is just a helper and can be replaced, with the functional difference highlighted below.
const rootElement = document.getElementById("root");
ReactDOM.render(
<Provider Context={Context}>
<App />
...
A side benefit to scoping the context state to the provider is allowing multiple entire apps to be run concurrently.
applyMiddleware(...middlewares)
This takes a variable list of middlewares to be applied.
Example: Custom Logger Middleware
function logger({ getState }) {
return (next) => async (action) => {
console.log("will dispatch", action);
const returnValue = await next(action);
console.log("state after dispatch", getState());
return returnValue;
};
}
export default createContext(..., applyMiddleware(logger));
See redux applyMiddleware for more documentation.
Demo
As a proof of concept see the converted sandbox app from the react-redux basic tutorial below.
References
Lots of inspiration from the following tools