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.
useReducer
like in this code sample akin to the redux helper, 2) have multipleuseReducer
s/state trees published in a single context, 3) create multiple contexts, one for eachuseReducer
. For eachuseReducer
, you also can separate the dispatch and state. It just depends on the purpose - size of your app, scalability, encapsulation etc. – Blondellblondelle