How to implement React useReducer for multiple state objects in a single provider

Viewed 1195

We have three related but separate gigantic state objects in one provider and aren't sure which way is better to implement useReducer.

We're in the middle of migrating to use useReducer and it would be hard to manage sticking them all in a single initialState.

const initialStateA = {
  ...
}

const initialStateB = {
  ...
}

const initialStateC = {
  ...
}

Option 1: one single 'mainReducer' to manage everything

const mainReducer = ({reducerA, reducerB, reducerC}, action) => {
  // reducerA + reducerB + reducerC....
}

const [state, dispatch] = useReducer(mainReducer, {...initialStateA, ...initialStateB, ...initialStateC})

Option 2: having three separate useReducers

const [stateA, dispatchA] = useReducer(reducerA, initialStateA)
const [stateB, dispatchB] = useReducer(reducerB, initialStateB)
const [stateC, dispatchC] = useReducer(reducerC, initialStateC)

Which approach is better? What are the pros/cons for each or is there little/no difference between the two?

1 Answers

If the these three gigantic state objects don't communicate each other, and each one will be used in different sub-apps, I would split the reducers into separate providers as recommended by redux style guide - Only One Redux Store Per App

Related