react-duck
v0.5.4
Published
🦆 React ducks without Redux
Downloads
42
Maintainers
Readme
React Duck
Implement ducks in React following the redux pattern but using React Context.
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" },
});
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,
"ContextName",
enhancer,
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 = state[counterDuck.name];
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(state => state[counterDuck.name], 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>{state[counterDuck.name]}</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.
createConnect(Context?)
This a helper creates a function that can be used to smartly connect a component to your context value.
// connect.js
export default connect = createConnect(Context);
Note: if the Context
argument is not supplied, the GlobalContext
is used.
Note: createConnect
is just a helper and can be replaced with a direct import and use of connect
.
Example Usage
// app.jsx
function App(props) {
return (
<div>
Count: <span>{props.count}</span>
<button onClick={props.increment} />
</div>
);
}
export default connect(
(state) => ({ count: state[counterDuck.name] }),
(dispatch) => bindActionCreators(dispatch, counterDuck.actions)
)(App);
See redux connect for more options.
Demo
As a proof of concept see the converted sandbox app from the react-redux basic tutorial below.
Suggestions
- Use
immer
to create immutable reducers, see guide