6

Working on React app where I have some global state defined with a single reducer currently but would like to introduce multiple reducer as the app is kinda large so would be easier and nicer to organize state on multiple reducers!

Currently I have:

import { StoreProvider } from './store'
const app = (
  <StoreProvider>
    <App />
  </StoreProvider>
)

store looks like:

import React, { useReducer, createContext } from 'react'
import { ApplicantState } from './interfaces/ApplicantState'
import applicantReducer from './modules/Applicant/ApplicantReducer'

const initialState: ApplicantState = {
  applicants: [],
  total: 0,
}

export const GlobalStore = createContext<ApplicantState | any>(initialState)
export const StoreProvider = ({ children }: JSX.ElementChildrenAttribute): JSX.Element => {
  const [state, dispatch] = useReducer(applicantReducer, initialState)
  return <GlobalStore.Provider value={{ state, dispatch }}>{children}</GlobalStore.Provider>
}

I would like to have another reducer, for ex userReducer how would I do that so I can call dispatch for multiple reducers, or should I use different context for each reducer? Any idea how to handle this?

Appreciate a lot examples.

Lulzim Fazlija
  • 865
  • 2
  • 16
  • 37
  • 1
    You can 1) combine reducers for a single `useReducer` like in [this code sample](https://stackoverflow.com/a/57298115/5669456) akin to the redux helper, 2) have multiple `useReducer`s/state trees published in a single context, 3) create multiple contexts, one for each `useReducer`. For each `useReducer`, you also can separate the dispatch and state. It just depends on the purpose - size of your app, scalability, encapsulation etc. – ford04 Mar 31 '20 at 15:40
  • Hi, I presume your listing order is based on which option is best! If not could you tell me which of the above would be the best? app is medium size – Lulzim Fazlija Apr 01 '20 at 06:38
  • No, the list is ordered by increasing complexity, there is no "best" way. Just think about the *concrete* reason, why you feel the need to refactor in the first place. Then you can choose the appropriate solution *for your app* automatically - in general I would start with the simplest alternative possible (1,2), until you realize, it is not sufficient anymore, then gradually upgrade. – ford04 Apr 01 '20 at 08:37
  • your question is answered here https://stackoverflow.com/questions/59200785/react-usereducer-how-to-combine-multiple-reducers – mohammad barzegar Jul 10 '21 at 11:42

0 Answers0