Skip to content

Instantly share code, notes, and snippets.

@destinio
Created June 22, 2021 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save destinio/1904562e101e2fda40366d8bd68dd1bb to your computer and use it in GitHub Desktop.
Save destinio/1904562e101e2fda40366d8bd68dd1bb to your computer and use it in GitHub Desktop.
import React, { createContext, useContext, useReducer } from 'react'
interface StateInterface {
data: string[]
}
interface Actions {
type: string
payload: any
}
type AppContextType = {
state: StateInterface
dispatch: React.Dispatch<Actions>
}
const AppContext = createContext<AppContextType>(null!)
export function useAppContext(): AppContextType {
return useContext(AppContext)
}
const initState = {
data: []
}
function appReducer(state: StateInterface, action:Actions) {
switch (action.type) {
case 'SET_DATA':
return {...state, data: [...state.data, action.payload]}
default:
return state
}
}
type Props = {
children: React.ReactNode
}
export default function AppContextProvider({children}: Props): React.ReactElement {
const [state, dispatch] = useReducer(appReducer, initState)
return <AppContext.Provider value={{ state, dispatch }}>{children}</AppContext.Provider>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment