Wrap useReducer to log every action and state change. Great for debugging.
import { useReducer, Reducer } from 'react';
export function useReducerWithLogger<S, A>(
reducer: Reducer<S, A>,
initialState: S,
label = 'state'
): [S, (action: A) => void] {
const [state, dispatch] = useReducer(reducer, initialState);
const dispatchWithLog = (action: A) => {
console.log(`[${label}] action:`, action, 'prev:', state);
dispatch(action);
};
return [state, dispatchWithLog];
}Use in development to log every action and resulting state. Same API as useReducer; pass reducer, initial state, and optional label.
Drop-in replacement. Strip or guard with NODE_ENV in production.
const [state, dispatch] = useReducerWithLogger(myReducer, initialState, 'cart');