redux-hook-middleware

raw JSON →
0.1.22 verified Sat Apr 25 auth: no javascript

A Redux middleware that allows registering pre- and post-dispatch hooks for specific action types. Version 0.1.22, likely low or no active releases. It provides functions like registerPrehook, registerPosthook, and unregisterHook to attach callbacks that execute before or after an action is dispatched. The middleware is simple and lightweight, differentiating from saga or thunk by offering a straightforward hook mechanism without generator functions or promises. It is suitable for small to medium Redux applications needing cross-cutting concerns like logging or side effects tied to specific actions.

error Uncaught Error: Could not find hookMiddleware in the middleware chain
cause The library expects hookMiddleware to be applied, but it was not added to applyMiddleware.
fix
Ensure hookMiddleware is included in the middleware array: applyMiddleware(hookMiddleware, ...otherMiddlewares)
error registerPrehook is not a function
cause Incorrect import; trying to use default import instead of named import.
fix
Use named import: import { registerPrehook } from 'redux-hook-middleware'
error TypeError: hookId is not a symbol
cause unregisterHook expects a Symbol returned from registerHook, but a string or number was passed.
fix
Store the symbol returned from registerPrehook/registerPosthook and pass it to unregisterHook.
gotcha Hooks are called synchronously; cannot use async callbacks for side effects without additional handling.
fix If you need async side effects, use redux-thunk or redux-saga, or wrap async logic inside a thunk action.
gotcha registerPrehook and registerPosthooks have a typo ('onject' in the README) which may cause confusion.
fix Use registerPosthooks (with 's') for registering multiple hooks.
gotcha Hook callbacks receive a limited store API (getState, dispatch) but not the full Redux store.
fix Use the provided store parameter; it is not the full store but a wrapped version with getState and dispatch.
npm install redux-hook-middleware
yarn add redux-hook-middleware
pnpm add redux-hook-middleware

Setup Redux store with hookMiddleware, register a pre-hook for INCREMENT action, and see it log before state update.

import { createStore, applyMiddleware } from 'redux';
import hookMiddleware, { registerPrehook } from 'redux-hook-middleware';

const initialState = { count: 0 };
const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    default:
      return state;
  }
};

const store = createStore(reducer, applyMiddleware(hookMiddleware));

registerPrehook('INCREMENT', (store, action) => {
  console.log('About to increment, current count:', store.getState().count);
});

store.dispatch({ type: 'INCREMENT' }); // logs: About to increment, current count: 0