Creating a Context for a global state
Based on the React Context behavior, we will discuss two solutions regarding using Context with a global state, as follows:
- Creating small state pieces
- Creating one state with
useReducer
and propagating with multiple Contexts
Let's take a look at each solution.
Creating small state pieces
The first solution is to split a global state into pieces. So, instead of using a big combined object, create a global state and a Context for each piece.
The following example creates two count
states, with a Context and a provider component for each count
state.
Firstly, we define two Contexts, Count1Context
and Count2Context
, one for each piece, as follows:
type CountContextType = [ number, Dispatch<SetStateAction<number>> ]; const Count1Context = createContext<CountContextType>([ 0, () => {} ]); const Count2Context = createContext<CountContextType...