import { createContext, useReducer, ReactChildren } from 'react' type Action = | { type: 'beHappy' } | { type: 'addReason', reason: string } type State = { isHappy: boolean reasons: string[] } type Context = { state: State, dispatch: React.Dispatch } function reducer(state: State, action: Action): State { switch (action.type) { case 'beHappy': return { ...state, isHappy: true } case 'addReason': return { ...state, reasons: [...state.reasons, action.reason] } default: return state } } const initialState: State = { isHappy: false, reasons: [] } const initialContext: Context = { state: initialState, dispatch: () => { } } const Store = createContext(initialContext) interface ProviderProps { children: ReactChildren } const StoreProvider = (props: ProviderProps) => { const [state, dispatch] = useReducer(reducer, initialState) return ( {props.children} ) } export { StoreProvider, Store }