Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

functions for creating and composing reducers and middleware efficiently

License

NotificationsYou must be signed in to change notification settings

jcoreio/redux-utils

Repository files navigation

CircleCICoverage Statussemantic-releaseCommitizen friendlynpm version

Making Redux scalable

If you usecombineReducers to create your top-level reducer, it will call every one of your subreducers for every action you dispatch. This is easy to debug, and it ensures your state will update correctly, but it's easy to imagine how it will create performance problems.

Imagine you're combining 100 subreducers, and you're dispatching actions from amousemove listener at 60 Hz. That's 6000 subreducer calls per second, and it only increases as you add more slices to your state and corresponding subreducers to your app.

This package andmindfront-redux-utils-immutable help you create and combine reducers and middleware in such a way that only the relevant subreducer(s) and middleware for a given action are called, so you don't have to worry that performance will decrease with every subreducer or sub-subreducer (etc) you add.

There is a downside to this approach: debugging is more difficult, because it's harder to trace where a subreducer is getting called from (or why it's not getting called). This package tries to mitigate that problem as much as it can by saving stack traces of where reducers were created and combined.

Legacy build note

If you are building for legacy browsers with webpack or similar bundlers, make sure to add a ruleto transpile this package with babel.

createReducer([initialState: any,] actionHandlers: {[actionType: string]: Reducer}): Reducer

import{createReducer}from'mindfront-redux-utils'

Creates a reducer that delegates toactionHandlers[action.type], if it exists, and otherwise, returnsstate.IfinitialState is provided, it will be used as the initial state if the reducer is called with undefinedinitial state.

The returned reducer will also haveinitialState andactionHandlers as own properties (primarily so thatcomposeReducers can efficiently compose action map reducers).

composeReducers(...reducers: Reducer[]): Reducer

import{composeReducers}from'mindfront-redux-utils'

Creates a reducer that applies all the provided reducers.

If any consecutive reducers have anactionHandlers property that is an object (for instance reducers made withcreateReducer),composeReducers will compose them efficiently: it will group the action handlers by type,compose the handlers for each type separately, and then usecreateReducer on the composed action handlers,and initial state from the first reducer for whichinitialState is defined.

createMiddleware(actionHandlers: {[actionType: string]: Middleware}): Middleware

import{createMiddleware}from'mindfront-redux-utils'

Creates middleware that delegates toactionHandlers[action.type], if it exists, and otherwise,returnsnext(action).

The returned middleware will also haveactionHandlers as an own property.

composeMiddleware(...middlewares: Middleware[]): Middleware

import{composeMiddleware}from'mindfront-redux-utils'

Composes the given middlewares to be called one after another, just like Redux'applyMiddleware, but with oneoptimization: sequences of consecutive middleware that haveactionHandlers will be recombined into a single middlewarethat calls anyactionHandlers for a given action directly.

applyMiddleware(...middlewares: Middleware[]): createStore => createStore'

Requiresredux as an optional dependency.

importapplyMiddlewarefrom'mindfront-redux-utils/lib/applyMiddleware'

Just likeapplyMiddleware fromredux, but applies the same optimization ascomposeMiddleware: sequences ofconsecutive middleware that haveactionHandlers will be recombined into a single middleware that calls anyactionHandlers for a given action directly.

combineMiddlewareWithActionHandlers(...middlewares: Middleware[]): Middleware[]

import{combineMiddlewareWithActionHandlers}from'mindfront-redux-utils'

Replaces any sequences of consecutive middleware that haveactionHandlers in the arguments with a single middlewarethat calls theactionHandlers for a given action directly. (This is used bycomposeMiddleware under the hood).

createPluggableMiddleware(initialMiddleware: Middleware): Middleware

import{createPluggableMiddleware}from'mindfront-redux-utils'

Creates a middleware that delegates to a hot-swappable middleware. The returned middleware will have areplaceMiddleware(nextMiddleware: Middleware) function. This way you can use Webpack hot reloading onyour custom middleware.

prefixReducer(prefix: string): (reducer: Reducer) => Reducer

import{prefixReducer}from'mindfront-redux-utils'

A reducer decorator that stripsprefix from eachaction.type before passing it to the decoratedreducer.If theaction.type doesn't start withprefix, it will just return thestate instead of callingreducer.

If the decorated reducer hasactionHandlers (fromcreateReducer), then the returned reducer will haveactionHandlers with the prefixed action type keys.

Example

import{combineReducers}from'redux'import{createReducer,prefixReducer}from'mindfront-redux-utils'constcounterReducer=createReducer(0,{DECREMENT:(state)=>state-1,INCREMENT:(state)=>state+1,})constreducer=combineReducers({counter1:prefixReducer('COUNTER_1.')(counterReducer),counter2:prefixReducer('COUNTER_2.')(counterReducer),})reducer({},{type:'COUNTER_1.INCREMENT'})// {counter1: 1}reducer({counter1:3,counter2:3},{type:'COUNTER_1.DECREMENT'})// {counter1: 2, counter2: 3}reducer({counter1:3,counter2:3},{type:'COUNTER_2.INCREMENT'})// {counter1: 3, counter2: 4}

prefixActionCreator(prefix: string): (actionCreator: ActionCreator) => ActionCreator

import{prefixActionCreator}from'mindfront-redux-utils'

An action creator decorator that prependsprefix to thetype of the created actions.

Example

import{prefixActionCreator}from'mindfront-redux-utils'functionsetEntry(key,value){return{type:'SET_ENTRY',payload:value,meta:{ key},}}constsetConfigEntry=prefixActionCreator('CONFIG.')(setEntry)setConfigEntry('hello','world').type// CONFIG.SET_ENTRY

addMeta(meta: Object): (actionCreator: ActionCreator) => ActionCreator

import{addMeta}from'mindfront-redux-utils'

An action or action creator decorator that assigns additional properties to actions'meta.

Example

import{addMeta}from'mindfront-redux-utils'functionsetEntry(key,value){return{type:'SET_ENTRY',payload:value,meta:{ key},}}constforConfigDomain=addMeta({domain:'config'})constsetConfigEntry=forConfigDomain(setEntry)setConfigEntry('hello','world').meta// {key: 'hello', domain: 'config'}forConfigDomain(setEntry('hello','world')).meta// {key: 'hello', domain: 'config'}

fullStack(error: Error, wrapped?: (error: Error) => string): string

Errors thrown from the sub-reducers you pass tocreateReducer,composeReducers, 'prefixReducer', or sub-middlewareyou pass tocreateMiddleware orcomposeMiddleware normally don't include any information about where the associatedcall tocreateReducer etc. occurred, making debugging difficult. However, in dev mode,mindfront-redux-utils addsthis info to the resulting reducers and middleware, and you can get it by callingfullStack, like so:

import{createReducer,fullStack}from'./src'functionhello(){thrownewError('TEST')}constr=createReducer({ hello})try{r({},{type:'hello'})}catch(e){console.error(fullStack(e))}

Output:

Error: TEST    at hello (/Users/andy/redux-utils/temp.js:4:9)    at result (/Users/andy/redux-utils/src/createReducer.js:19:24)    at withCause (/Users/andy/redux-utils/src/addCreationStack.js:5:14)    at Object.<anonymous> (/Users/andy/redux-utils/temp.js:9:3)    at Module._compile (module.js:556:32)    at loader (/Users/andy/redux-utils/node_modules/babel-register/lib/node.js:144:5)    at Object.require.extensions.(anonymous function) [as .js] (/Users/andy/redux-utils/node_modules/babel-register/lib/node.js:154:7)    at Module.load (module.js:473:32)    at tryModuleLoad (module.js:432:12)    at Function.Module._load (module.js:424:3)Caused by reducer created at:    at addCreationStack (/Users/andy/redux-utils/src/addCreationStack.js:2:21)    at createReducer (/Users/andy/redux-utils/src/createReducer.js:25:55)    at Object.<anonymous> (/Users/andy/redux-utils/temp.js:6:11)    at Module._compile (module.js:556:32)    at loader (/Users/andy/redux-utils/node_modules/babel-register/lib/node.js:144:5)    at Object.require.extensions.(anonymous function) [as .js] (/Users/andy/redux-utils/node_modules/babel-register/lib/node.js:154:7)    at Module.load (module.js:473:32)    at tryModuleLoad (module.js:432:12)    at Function.Module._load (module.js:424:3)    at Function.Module.runMain (module.js:590:10)

If you are usingVError, you may pass VError'sfullStack function as thesecond argument to also include the cause chain fromVError.

About

functions for creating and composing reducers and middleware efficiently

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors4

  •  
  •  
  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp