react-ducks
v0.6.3
Published
🦆 React ducks without Redux
Downloads
62
Maintainers
Readme
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.
// duck/counter.js
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);
// this is equivalent to (rootState) => rootState[counterDuck.name]
Create the root/global duck as a combination of all other ducks.
// duck/index.js
export default createRootDuck(counterDuck, otherDuck);
Create the global context.
// context.js
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.
// app.jsx
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.
// app.jsx
...
const count = useSelector(counterDuck.selectors.$, Context);
const increment = useDispatch(counterDuck.actions.increment, Context);
...
Note: This is equivalent to the class component described below.
// app.jsx
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.
// index.jsx
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.
// index.jsx
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
// context.js
function logger({ getState }) {
// Recommend making the returned dispatch method asynchronous.
return (next) => async (action) => {
console.log("will dispatch", action);
// Call the next dispatch method in the middleware chain.
const returnValue = await next(action);
// Resolving the result of the next dispatch allows the referenced
// state to be updated by `React.useReducer` and available to get.
console.log("state after dispatch", getState());
// This will likely be the action itself, unless
// a middleware further in chain changed it.
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