Typing Context in React

January 8, 2022

Typing Context in React

Problem: Context is not typed

I was using context and TypeScript was yelling at me.

"keyword">import React, { createContext, useContext } from "react"
"keyword">const AppContext = createContext({})
"keyword">const useAppContext = () => useContext(AppContext)
"keyword">export { AppContext, useAppContext }

Before I reveal the solution, let's look at the problem

The context is not typed. This is a problem because TypeScript is not able to infer the type of the context.

This is how I got TypeScript to infer the type of the context

interface MyContextInterface {
  name: string
  hobbies: Hobby[]
}

## create a default value "keyword">for the context

```ts
"keyword">const defaultContextValue: MyContextInterface = {
  name: "",
  hobbies: [],
};

Finally, pass the default value to

"keyword">const MyContext = createContext(defaultContextValue)

Next create the provider

"keyword">const MyContextProvider = ({ children }) => {
  "keyword">const [name, setName] = useState("")
  "keyword">const [hobie, setHobie] = useState([])

  "keyword">return (
    
      {children}
    
  )
}

define a hook to use the context

"keyword">const useMyContext = () => useContext(MyContext)

export the context, provider, and hook as named exports

"keyword">export { MyContext, MyContextProvider, useMyContext }

wrap your App component with the a your context provider

"keyword">const App = () => {
  "keyword">return (
    
      
    
  )
}

this is how to useMyContext hook without having to pass props

"keyword">import { useMyContext } from "./MyContext"

"keyword">const DeepChild = () => {
  "keyword">const { name, hobies } = useMyContext()
  "keyword">return (
    

{name}

    {hobies.map((hobie) => (
  • {hobie}
  • // programming, kiteboarding, surfing, running ))}
) }

Celebrate, typeScript is now able to infer the type of the context! 😀

learn more about React Context

learn more about TypeScript

learn more about React

learn more about React Hooks

Disclaimer: The views and opinions expressed in this blog post are solely my own and do not reflect the views of my employer, colleagues, or any affiliated organization.