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.

import React, { createContext, useContext } from "react" const AppContext = createContext({}) const useAppContext = () => useContext(AppContext) 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 for the context ```ts const defaultContextValue: MyContextInterface = { name: "", hobbies: [], };

Finally, pass the default value to

const MyContext = createContext(defaultContextValue)

Next create the provider

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

define a hook to use the context

const useMyContext = () => useContext(MyContext)

export the context, provider, and hook as named exports

export { MyContext, MyContextProvider, useMyContext }

wrap your App component with the a your context provider

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

this is how to useMyContext hook without having to pass props

import { useMyContext } from "./MyContext" const DeepChild = () => { const { name, hobies } = useMyContext() 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.