how to combine multiple reducers in React using Context API

Viewed 3687

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.

0 Answers
Related