React Context with Typescript

Hi everyone I have a question when it comes to Context API together with Typescript.

Here is a simple example how to use context API, with a reducer function.
My question is how would I would use it with typescript fully typed ?

Thank you everyone for helping! // Marcell

import React, { useReducer, useContext } from 'react'

const CounterStateContext = React.createContext()
const CounterDispatchContext = React.createContext()

const reducer = (state, action) => {
  switch (action.type) {
    case 'INCREASE':
      return state + 1
    case 'DECREASE':
      return state - 1
    case 'INCREASE_BY':
      return state + action.payload
      throw new Error(`Unknown action: ${action.type}`)

export const CounterProvider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, 0)
  return (
    <CounterDispatchContext.Provider value={dispatch}>
      <CounterStateContext.Provider value={state}>

export const useCount = () => useContext(CounterStateContext)
export const useDispatchCount = () => useContext(CounterDispatchContext)

You can define your own context type.

import React from "react";

const MyContext = React.createContext({
    foo: 'bar'

export default MyContext;

And then use it with const {foo} = useContext(MyContext)



Thank you, Ben, I will definitely try it out :grinning: