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
    default:
      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}>
        {children}
      </CounterStateContext.Provider>
    </CounterDispatchContext.Provider>
  )
}

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)

HTH,
Ben

2 Likes

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