how to combine multiple reducers in React using Context API
Asked Answered
G

0

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.

Galiot answered 31/3, 2020 at 11:3 Comment(4)
You can 1) combine reducers for a single useReducer like in this code sample akin to the redux helper, 2) have multiple useReducers/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.Blondellblondelle
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 sizeGaliot
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.Blondellblondelle
your question is answered here #59201285Vries

© 2022 - 2024 — McMap. All rights reserved.