npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

redux-reuse

v0.4.3

Published

Reuse code in redux reducers

Downloads

38

Readme

redux-reuse

redux-reuse is a Redux-related project, which provides extendReducer() helper function, which helps to make your reducers code DRY, based on approach of composable higher-order reducers.

extendReducer() allows you to add logic to reducer after it has been created, in other words you extend reducers. Using extendReducer() it is pretty simple to write composable higher-order reducers for your Redux application, at the end of the day most reducers can be presented as composition of higher-order reducers.

Usage

Install via NPM

npm install redux-reuse --save

Import

import { extendReducer } from 'redux-reuse';
// or
var reduxReuse = require('redux-reuse');

If you need ES6 module

import { extendReducer } from 'redux-reuse/es6';

Use this if you are using rollup.js or webpack 2, or any ES2015 modules-compatible bundler which can eliminate unused library code with tree-shaking.

It is recommended to import the library from redux-reuse/es6 instead of redux-reuse/src because the source code depends on experimental presets from babel (stage 1-3) and may be incompatible with your bundler or settings.

Other environments

Use the Universal Module Definition (UMD)

API

extendReducer()

extendReducer(
  handlers: {
    [actionType: string] => (state: any, action: Object) => any
  },
  propagate: ?boolean = true
): (reducer) => reducer

// Uncurried
extendReducer(
  reducer,
  handlers: {
    [actionType: string] => (state: any, action: Object) => any
  },
  propagate: ?boolean = true
): reducer

Extends a reducer with additional action handlers. It means that new reducer will be returned, which wraps the original one and once an action with one of specified action types occurs, the appropriate handler will be executed first and then based on propagate argument the result will or will not be passed on to the original reducer.

In other words extendReducer() extends the existent reducer with some logic, which will be performed on specified actions. With extendReducer() it is pretty easy to write composable higher-order reducers which are specific to your application and reuse them in you reducers. See below examples for how to do it.

initialReducer()

initialReducer(initialState: any): reducer

Creates a reducer with passed value as initial state.

nullReducer

nullReducer: reducer

A reducer which returns null as the initial state.

Overview of existent approaches to reuse code in reducers

There are several approaches for how to organize your reducers code as reusable pieces:

  • Organize your common logic in functions and use that functions in you reducers.

Basic approach to reuse pieces of code :)

  • Create you own reducer for each usecase and use combineReducers() helper in order to combine separate reducers.

This approach has two disadvantages: first of all it will produce deeper state tree, so once your application will grow it can lead you to huge selectors, and secondly this way will not cover case when you need to manage one piece of state.

  • Split logic to separate maps of handlers, where keys are action types and values are appropriate reducers, then use Object.assign(oneReducerMap, anotherReducerMap) or spread operator to combine maps and use their combination in some helpers like handleActions() from redux-actions or createReducer() from redux-create-reducer to initialize your reducer, which will be superset of combined reducer maps.

This approach also has disadvantage: if you have two reducer maps, which should perform some logic on same actions, then as result of merging maps, one of them will overwrite another one, so only logic from one reducer map will be performed when contradicted action occurs.

  • Organize common logic in separate reducers, cummulate needed reducers in array and reduce them into single reducer via reduceReducers() helper from reduce-reducers.

This approach let you achieve the same result, as extendReducer(), but last one is more Redux-oriented (like using handleActions() or createReducer() to create reducers) and it helps to operate in terms of composable higher-order reducers, which means control over execution of base reducer. So choose what you need :)

Example of how to use extendReducer() to write your own higher-order reducers.

You can look at ready-to-use higher-order reducers, which has been implemented using extendReducer() helper:

And start organizing your reducers code in reusable pieces like in the following example:

Let's imagine that we have two separate counters and they should provide different behaviours on each tick that occurs. One should only increment its own by 1 and the other one should also change sign of a number it holds. And you have two separate widgets with such a counters, which work independently and start with different numbers.

import { compose, combineReducers } from 'redux';
import { extendReducer, initialReducer } from 'redux-reuse';
import { WIDGET1_TICK, WIDGET2_TICK } from 'event-types';

const increment = (actionType) => (reducer) =>
  extendReducer(reducer, {
    [actionType]: (state) => state + 1
  });

const changeSign = (actionType) => (reducer) =>
  extendReducer(reducer, {
    [actionType]: (state) => state * (-1)
  });

const widgetReducer = (tickActionType, startingNumber) =>
  combineReducers({
    smoothCounter: increment(tickActionType)(initialReducer(startingNumber)),
    jumpingCounter: compose(
      increment(tickActionType),
      changeSign(tickActionType)
    )(initialReducer(startingNumber))
  });

const app = combineReducers({
  widget1: widgetReducer(WIDGET1_TICK, 0),
  widget2: widgetReducer(WIDGET2_TICK, 100)
})

As you can see everything is reused! :)

Another interesting example is when you need to plug-in and plug-out some functionality. Lets imagine we have counter with checkboxes, indicating what exact functionality should be turned on.


import { extendReducer, initialReducer } from 'redux-reuse';
import { PUSH_MODE, POP_MODE, TICK } from 'event-types';
import { INCREMENT, SQUARE, CHANGE_SIGN } from 'modes';

const increment = (actionType) => (reducer) =>
  extendReducer(reducer, {
    [actionType]: (state) => state + 1
  });

const square = (actionType) => (reducer) =>
  extendReducer(reducer, {
    [actionType]: (state) => state * state
  });

const changeSign = (actionType) => (reducer) =>
  extendReducer(reducer, {
    [actionType]: (state) => state * (-1)
  });

const modesMap = {
  [INCREMENT]: increment,
  [SQUARE]: square,
  [CHANGE_SIGN]: changeSign,
};

const counter = (state = { modes: [], value: null }, { payload: mode }) => {
  switch (action.type) {
    case PUSH_MODE:
      state.modes.push(mode);
      break;
    case POP_MODE:
      state.modes.pop();
      break;
    case TICK:
      const reducers = state.modes.map((mode) => modesMap[mode]);
      state.value = compose(...reducers)(initialReducer(0))(state.value, action);
      break;
  }

  return state;
};

And again, we can reuse our higher-order reducers in every place we wish.

Thanks

Big thanks to ilyagelman for reviewing and acting as opponent, which helped a lot in preparing the overview of existent approaches.