importtype{ Dispatch }from'react';exporttypeState={};// These are utility types and can be exported somewhere elsetypeAction<Textendsstring,P>={ type:T; payload:P};typeActionWithoutPayload<Textendsstring>={ type:T};// These are the actions that can be dispatchedtypeReset= ActionWithoutPayload<"RESET">;typeUpdateField= Action<"UPDATE_FIELD",{ name:string; value:unknown}>// be more specific than meexporttypeActions= Reset | UpdateField;exporttypeContextState= State &{// Some people create two layers of context for state & dispatch,// do what you feel is best for your project dispatch: Dispatch<Actions>}
import{ produce }from'immer';importtype{ State, Actions }from'./types'// Used for resetting - if you have a `initialState` object,// make sure to store that as a `readonly` property in your `State` type to reference here.exportfunctioninitState(): State {}exportfunctionreducer(state: State, action: Actions){if(action.type ==='RESET')returninitState();returnproduce(state,(draft)=>{switch(action.type){case'UPDATE_FIELD':{const{ name, value }= action.payload; draft[name]= value;break;}}return draft})}
Immer does export a useImmerReducer hook, I don’t use that. If I decide to rip out immer, I’ll just need to re-implement my reducer function and not shuffle type definitions or alter my context definition.
import{ createContext, useContext, useMemo, useReducer,typePropsWithChildren}from'react'import{ reducer, initState }from'./reducer'importtype{ContextState}from'./types'constContext=createContext<ContextState |undefined>(undefined)// we'll guard agains't this in our hookexportconstProvider=({ children }:PropsWithChildren)=>{const[state, dispatch]=useReducer<typeof reducer, ContextState>( reducer,{}asContextState,()=>initState())const value =useMemo(()=>({ state, dispatch }),[state, dispatch])return<Context.Providervalue={value}>{children}</Context.Provider>}exportconstuseContextState=()=>{const context =useContext(Context)if(context ===undefined){thrownewError('useContextState must be used within a Provider')}return context}
This is very much a boilerplate to get you started. Very important, if you’ve got a large application and need global stores, look at other solutions like Zustand or Jotai, they do a much better job at reducing unnecessary re-renders. This pattern should wrap small parts of a application, such as a form experience or in a Micro Context pattern.
You can customise the ContextState type to include computed values which you’ll compute using a useMemo or inline in the Provider. You can also add additional props to the Provider to determine the initial state, remember to store these values for later use in the RESET action.
Also also, rename these functions/types/files to be more specific to your use case. I’ve used State and Actions as generic names, but you should be more specific to your use case.