Reducers are responsible for taking the current state and an action, and returning a new state instance.
Best Practices:
- Use static methods decorated with
[ReducerMethod]. - Reducers should be pure functions; avoid injecting dependencies into them. If you need side effects or dependencies, use an Effect instead.
- You can split reducer methods across multiple static classes; Fluxor will find them via assembly scanning.
Handling unused parameters:
If a reducer method receives an action but doesn't use its properties, you can avoid compiler warnings by specifying the action type in the attribute: [ReducerMethod(typeof(MyAction))].
Alternative Pattern:
You can inherit from Reducer<TState, TAction>, but this is generally not recommended as it requires more boilerplate than static methods.
public static class Reducers
{
[ReducerMethod]
public static CounterState ReduceIncrementCounterAction(CounterState state, IncrementCounterAction action) =>
new CounterState(clickCount: state.ClickCount + 1);
}
// Reducer avoiding unused parameter warning
[ReducerMethod(typeof(IncrementCounterAction))]
public static CounterState ReduceIncrementCounterAction(CounterState state) =>
new CounterState(clickCount: state.ClickCount + 1);
// Alternative (not recommended) inheritance pattern
public class IncrementCounterReducer : Reducer<CounterState, IncrementCounterAction>
{
public override CounterState Reduce(CounterState state, IncrementCounterAction action) =>
new CounterState(clickCount: state.ClickCount + 1);
}