React Contexts with Typescript

import {createContext, Dispatch, ReactNode, Reducer, useContext, useReducer} from "react";import { Action } from "../reducers/reducer";export interface State {example: string;}export const StateContext = createContext<[State, Dispatch<Action>]>(undefined!);export const StateProvider = ({reducer,children,}: {reducer: Reducer<State, Action>;children: ReactNode;}) => {const initialState = {example: "",};return (<StateContext.Provider value={useReducer(reducer, initialState)}>{children}</StateContext.Provider>);};export const useStateValue = () => {const stateContext = useContext(StateContext);if (stateContext === null) {throw new Error("useStateValue() can only be used inside of <StateProvider />, please declare it at a higher level.");}return stateContext;};
import {createContext, Dispatch, ReactNode, Reducer, useContext, useReducer,} from "react";import { Action } from "../reducers/reducer";export interface State {example: string;}export const StateContext = createContext<[State, Dispatch<Action>]>(undefined!);export const StateProvider = ({reducer,children,}: {reducer: Reducer<State, Action>;children: ReactNode;}) => {const initialState = {example: "",};return (<StateContext.Provider value={useReducer(reducer, initialState)}>{children}</StateContext.Provider>);};export const useStateValue = () => useContext(StateContext);

--

--

Make Things, Web3

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store