redux-higher-orders

Redux enhancer for composing higher order reducers

Usage no npm install needed!

<script type="module">
  import reduxHigherOrders from 'https://cdn.skypack.dev/redux-higher-orders';
</script>

README

redux-higher-orders

Redux enhancer for composing higher order reducers

Benefits

  • Simple enhancer method for adding higher order reducers to redux.
  • Wrap the reduce reducer with functionality ensuring that the higher order runs before the primary reducer.

Build Status

npm version
Build Status
NPM

Install

npm install --save redux-higher-orders

Usage

import { createStore } from 'redux'
import { applyHigherOrders } from 'redux-higher-orders'

const higherOrders = [
  reducer => (state, action) => reducer(state, action),
  higherOrder2,
  higherOrder3
]

let store = createStore(
  reducer,
  initialState,
  applyHigherOrders(...higherOrders)
)

applyHigherOrders(...higherOrders)

Higher order reducers are a way to extend the Redux reducer with custom functionality. Higher orders let you wrap the store's internal reducer method.

The most common use case for higher order reducers is to support modification of actions or state before/after reduction. An example is to support batching of actions

Arguments

  • ...higherOrders (arguments): Functions that conform to the higher-order API. Each higherOrder receives the reducer function and returns a reducer function. The higher orderThe higher order signature is (reducer) => (state, action) => reducer(state, action).

Returns

(Function) A store enhancer that applies the given higher-order. The store enhancer signature is createStore => createStore' but the easiest way to apply it is to pass it to createStore() as the last enhancer argument.

Example: Custom Logger Higher Order

import { createStore } from 'redux'
import { applyHigherOrders } from 'redux-higher-orders'
import todos from './reducers'

function logger() {
  return (reducer) => (state, action) => {
    console.log('will reduce', action)

    // Reduce the next state
    let resultState = reducer(state, action)
    console.log('state after dispatch', resultState)

    return resultState
  }
}

let store = createStore(
  todos,
  [ 'Use Redux' ],
  applyHigherOrders(logger())
)

store.dispatch({
  type: 'ADD_TODO',
  text: 'Understand higher orders'
})