Skip to main content

Reducers

Reducers – Pure State Updates

A reducer is a pure function that updates a specific part of the state in response to an action.

✨ Key Principles

Reducers:

  • Take the current state and an action
  • Return a new state
  • Must be pure — no side effects, service calls, or randomness
  • Are called after effects, if any exist

🚫 Async Tips

Reducers may return Task<TState>, but should avoid unnecessary await.

IncrementReducer.cs
internal class IncrementReducer : IReducer<CounterState, IncrementCounterResultAction>
{
public CounterState Reduce(CounterState state, IncrementCounterResultAction action)
=> state with { Count = action.Count };
}

⚙️ What are Reducer Middlewares?

StatePulse uses middleware interfaces to tap into the lifecycle of effects, reducers, and dispatches.
These middleware hooks are useful for logging, metrics, analytics, or debugging — but should never alter behavior or mutate state.

❗ Middleware is observational only — do not use it to change logic or outcomes.

IReducerMiddleware allows you to hook into the execution of any effect.

Available Hooks

  • BeforeReducing(object state, object action) – called before the reducer runs
  • AfterReducing(object state, object action) – called after the reducer runs

Example: Reducer Middleware

LoggingReducerMiddleware.cs
internal class LoggingReducerMiddleware : IReducerMiddleware
{
public Task AfterReducing(object state, object action)
{
Console.WriteLine($"{action.GetType().Name} Executed.");
return Task.CompletedTask;
}

public Task BeforeReducing(object state, object action)
{
Console.WriteLine($"{state.GetType().Name} {action.GetType().Name} Executed.");
return Task.CompletedTask;
}
}