Search code examples
javascriptreduxreact-redux

Redux enhancer example


I am new to redux. I would like know how I could create my own enhancer in redux. I didn't find any example to create enhancer. To create enhancers, So what arguments do I need to pass and what do I need to return? Is there any rule on creating custom enhancer?

In redux documentation about enhancer, found below two links (no sample or example code)

Redux documentation said that,

Middleware adds extra functionality to the Redux dispatch function; enhancers add extra functionality to the Redux store. ... A middleware which logs dispatched actions and the resulting new state. An enhancer which logs the time taken for the reducers to process each action.

So, I am not sure that custom middleware and custom enhancer coding rule are the same like below

const loggerMiddleware = storeAPI => next => action => {
  console.log('dispatching', action)
  let result = next(action)
  console.log('next state', storeAPI.getState())
  return result
}

So, my question is how to create custom enhancer?


Solution

  • Here is the store enhancer interface

    export type StoreEnhancer<Ext = {}, StateExt = never> = (
      next: StoreEnhancerStoreCreator<Ext, StateExt>
    ) => StoreEnhancerStoreCreator<Ext, StateExt>
    export type StoreEnhancerStoreCreator<Ext = {}, StateExt = never> = <
      S = any,
      A extends Action = AnyAction
    >(
      reducer: Reducer<S, A>,
      preloadedState?: PreloadedState<S>
    ) => Store<ExtendState<S, StateExt>, A, StateExt, Ext> & Ext
    

    enhancers are high-order functions that take createStore and return a new enhanced version of createStore. Take a look at this sample implementation.

    const ourAwesomeEnhancer = createStore => (reducer, initialState, enhancer) => {
      const store = createStore(monitoredReducer, initialState, enhancer);
      //  add enhancer logic
    
      return {
        ...store
        //   you can override the some store properties or add new ones
      };
    };
    

    There is an example in official doc:

    const round = number => Math.round(number * 100) / 100
    
    const monitorReducerEnhancer = createStore => (
      reducer,
      initialState,
      enhancer
    ) => {
      const monitoredReducer = (state, action) => {
        const start = performance.now()
        const newState = reducer(state, action)
        const end = performance.now()
        const diff = round(end - start)
    
        console.log('reducer process time:', diff)
    
        return newState
      }
    
      return createStore(monitoredReducer, initialState, enhancer)
    }
    
    export default monitorReducerEnhancer