redux-local v0.1.3
Redux Local
Redux helper for maintaining pseudo-local state in a single tree.
- npm:
npm install redux-local --save
While there are existing alternatives to managing pseudo-local state in Redux — redux-local adopts the following philosophies:
- Reducers should only exist in one place, rather than assigned to individual components;
- Be able to dictate which components are updated with
shouldComponentUpdate; - Provide an overt distinction between standard dispatches and pseudo-local dispatches;
- Allow actions to be written without pseudo-local actions in mind;
Getting Started
By providing only a handful of functions — localFor and bindLocalState — redux-local doesn't complicate the managing of pseudo-local state in components.
Begin by setting up the default state for the reducer using DEFAULT_STATE:
const INITIAL_STATE = {
[DEFAULT_STATE]: 0
};Setup the reducer using the id to resolve which component dispatched the action:
export default (state = INITIAL_STATE, action) => {
const { id } = action;
const getState = bindLocalState(state);
switch (action.type) {
case INCREMENT:
return { ...state, [id]: getState(id) + 1 };
}
return state;
};Destructure the id and dispatcher for the component, and then invoke localDispatch with your action:
render() {
const { counter } = this.props;
const { id, dispatch: localDispatch } = localFor(this);
return (
<div onClick={() => localDispatch(incrementAction())}>
{counter[id]}
</div>
);
}It's worth taking a look at how the example Counter component works with redux-local, as well as the source which is intended to be straight-forward.
Functions
bindLocalState: Is a helper function that takes thestateand yields the state slice that pertains to the passed action by using the uniqueidproperty. ReturnsDEFAULT_STATEif theiddoesn't yet exist instate;localFor: Takes the component instance —this— and yields both the uniqueidfor the component — orDEFAULT_STATEif no local dispatches have yet occurred — and thedispatchfunction which appends theidto the action.
Note: The localFor function takes an optional second parameter for passing the id property name for the action.