You can write in typeScript like this:

SomeContext.tsx:

Define your context and no need to define default value here.

import React, { createContext, useContext, useState } from 'react';

export interface SomeContextType {
    someValue: string;
    setSomeValue: React.Dispatch<React.SetStateAction<string>>;
}

const SomeContext = createContext<SomeContextType | undefined>(undefined);

export const useSomeContext = () => {
    const context = useContext(SomeContext);
    if (context === undefined) {
        throw new Error('context not found');
    }
    return context;
};

SomeComponent.tsx:

Define your component that uses the context.

import { useSomeContext } from 'SomeContext';

const SomeComponent = () => {
    const { someValue, setSomeValue } = useSomeContext();

    // Rest of your component code
}

App.tsx

Wrap your application with the SomeContext.Provider.

import { SomeContext, SomeContextType } from 'SomeContext';

const App = () => {
    const defaultValue: SomeContext = {
        someValue: '',
        setSomeValue: () => {}
    };

    const [someValue, setSomeValue] = useState<string>(defaultValue.someValue);

    return (
        <SomeContext.Provider value={{ someValue, setSomeValue }}>
            // Rest of your code
        </SomeContext.Provider>
    );
}

I think this approach is commonly seen as the best way when working with React Context in TypeScript.

Answer from Moazzam Ahmed on Stack Overflow
🌐
React
legacy.reactjs.org › docs › context.html
Context – React
For example, the code below will re-render all consumers every time the Provider re-renders because a new object is always created for value: class App extends React.Component { render() { return ( <MyContext.Provider value={{something: ...
🌐
React
react.dev › reference › react › createContext
createContext – React
Wrap your components into a context provider to specify the value of this context for all components inside: ... Starting in React 19, you can render <SomeContext> as a provider.
Discussions

reactjs - Best way to use React Context (with useState) in Typescript - Stack Overflow
Sign up to request clarification or add additional context in comments. ... I agree, having to define (and maintain) default state is annoying (especially when there are several state values). I usually take the following approach: import React, { PropsWithChildren, useCallback, useEffect, ... More on stackoverflow.com
🌐 stackoverflow.com
When to use context?
Me personally, if I know state rarely changes. Instances like user authentication, app theme (dark, light, or whatever), something to that effect. If I'm not mistaken, react docs recommends using a query library from now on to handle server data fetching like React-Query or RTK Query (I could be wrong!!!). I've only used React-Query, but I have used Redux ToolKit. More on reddit.com
🌐 r/reactjs
4
4
May 5, 2023
React Context vs Zustand: Am I Missing Out on Anything?
You should ideally only use Context for sharing state which is contextual in nature. You should avoid using Context for global state. Zustand is more performant than context, lightweight, and really easy to learn. It can even be applied contextually, but it is made for global state by default. No good reason not to use it over Context. More on reddit.com
🌐 r/reactjs
21
6
July 5, 2023
Is there a reason not to use Redux as a replacement for Context?
Hi, I'm a Redux maintainer. The answer is that they really are different tools :) Context is a Dependency Injection tool for a single value, used to avoid prop drilling. Redux is a tool for predictable global state management, with the state stored outside React. Note that Context itself isn't the "store", or "managing" anything - it's just a conduit for whatever state you are managing, or whatever other value you're passing through it (event emitter, etc). I wrote an extensive article specifically to answer this frequently asked question, including details about what the differences are between Context and Redux, and when to consider using either of them - I'd recommend reading through this: Why React Context is Not a "State Management" Tool (and Why It Doesn't Replace Redux) More on reddit.com
🌐 r/reactjs
88
82
February 27, 2023
🌐
Devtrium
devtrium.com › posts › how-use-react-context-pro
How to use React Context like a pro - Devtrium
September 13, 2021 - In this example, the context is used to provide the logged-in user object to the app. This context is then consumed by the Page component that conditionally renders based on the user value.
Top answer
1 of 4
6

You can write in typeScript like this:

SomeContext.tsx:

Define your context and no need to define default value here.

import React, { createContext, useContext, useState } from 'react';

export interface SomeContextType {
    someValue: string;
    setSomeValue: React.Dispatch<React.SetStateAction<string>>;
}

const SomeContext = createContext<SomeContextType | undefined>(undefined);

export const useSomeContext = () => {
    const context = useContext(SomeContext);
    if (context === undefined) {
        throw new Error('context not found');
    }
    return context;
};

SomeComponent.tsx:

Define your component that uses the context.

import { useSomeContext } from 'SomeContext';

const SomeComponent = () => {
    const { someValue, setSomeValue } = useSomeContext();

    // Rest of your component code
}

App.tsx

Wrap your application with the SomeContext.Provider.

import { SomeContext, SomeContextType } from 'SomeContext';

const App = () => {
    const defaultValue: SomeContext = {
        someValue: '',
        setSomeValue: () => {}
    };

    const [someValue, setSomeValue] = useState<string>(defaultValue.someValue);

    return (
        <SomeContext.Provider value={{ someValue, setSomeValue }}>
            // Rest of your code
        </SomeContext.Provider>
    );
}

I think this approach is commonly seen as the best way when working with React Context in TypeScript.

2 of 4
3

I agree, having to define (and maintain) default state is annoying (especially when there are several state values). I usually take the following approach:

import React, { PropsWithChildren, useCallback, useEffect, useState } from 'react';

export interface SomeContextValue {
   someValue: string;
   someFunction: () => void;
}

// I generally don't export the Context itself.
// I export 'SomeProvider' for creating the context and 'useSomeContext' hook to consume it.
// That way, we can skip the type checking here and verify the actual values later (if necessary).
const SomeContext = React.createContext<SomeContextValue>({} as SomeContextValue);

// The provider is responsible for managing its own state.
// If you want to reuse it in slightly different ways, pass some extra props to configure it.
export const SomeProvider: React.FC<PropsWithChildren> = (props) => {

   // The state could be initialised via some default value from props...
   // const [someValue, setSomeValue] = useState(props.defaultValue);

   // ...or by some async logic inside a useEffect.
   const [someValue, setSomeValue] = useState<string>();
   useEffect(() => {
      loadSomeValue().then(setSomeValue);
   }, []);

   // wrapping the state-mutation function in useCallback is optional,
   // but it can stop unnecessary re-renders, depending on where the provider sits in the tree
   const someFunction = useCallback(() => {
      const nextValue = ''; // Some logic
      setSomeValue(nextValue);
   }, []);

   // We ensure the state value actually exists before letting the children render
   // If waiting for some data to load, we may render a spinner, text, or something useful instead of null
   if (!someValue) return null;

   return (
      <SomeContext.Provider value={{ someValue, someFunction }}>
         {props.children}
      </SomeContext.Provider>
   );
};

// This hook is used for consuming the context.
// I usually add a check to make sure it can only be used within the provider.
export const useSomeContext = () => {
   const ctx = React.useContext(SomeContext);
   if (!ctx) throw new Error('useSomeContext must be used within SomeProvider');
   return ctx;
};

Note: much of this boilerplate can be abstracted into a helper/factory function (much like @Andrew's makeUseProvider) but we found that made it more difficult for developers to debug. Indeed, when you yourself revisit the code in 6-months time, it can be hard to figure out what's going on. So I like this explicit approach better.

🌐
freeCodeCamp
freecodecamp.org › news › how-to-use-react-context
How to Use React Context in Your Project – Beginner's Guide
January 5, 2024 - This is where you pass the values ... the value prop. import React from 'react'; import MyContext from './MyContext'; const App = () => { const sharedValue = 'This is a shared value'; return ( <MyContext.Provider value={sharedValue}> ...
🌐
LoginRadius
loginradius.com › home
React's Context API Guide with Example
June 9, 2021 - 1import React, { useContext } from 'react' 2import ColorContextfrom './ColorContext' 3export const HomePage = () => { 4const colorValue= useContext(ColorContext) 5return <div>{ColorContext}</div> 6} We can update the context by updating the ...
🌐
Telerik
telerik.com › blogs › react-basics-how-when-use-react-context
React Basics: How and When to Use React Context
August 21, 2023 - Here’s a simple example of creating an authentication Context where Context contains information about the user state, whether the user is authenticated, and login/logout functions that can be used in any component of our app to update the user information and authentication status. import React, { createContext, useState } from "react"; export const AuthContext = createContext(); export const App = ({ children }) => { const [user, setUser] = useState(null); const [isAuthenticated, setIsAuthenticated] = useState(false); const login = (userData) => { // Authenticate user and set user informat
Find elsewhere
🌐
CodeMiner42
blog.codeminer42.com › home › react › you are using react context wrong or why we should not underestimate what we consider simple
You are using React Context WRONG Or why we should not underestimate what we consider simple - The Miners
March 19, 2024 - So we’ll change it… let’s make React fail LOUDLY. First of all, let’s recap the reason why this happened. Since you didn’t have any state to provide or modify when you were creating your context you had to provide a book with an empty name and an implementation for the changeName function that, for the lack of a better option, would do nothing.
🌐
Kent C. Dodds
kentcdodds.com › blog › how-to-use-react-context-effectively
How to use React Context effectively
What I suggest is you make a helper function within your context module which accepts dispatch along with any other data you need, and make that helper be responsible for dealing with all of that. Here's an example from my Advanced React Patterns workshop:
🌐
CRS Info Solutions
crsinfosolutions.com › home › step-by-step guide to react’s context api
Step-by-Step Guide to React's Context API
Salesforce Training
This approach has established CRS Info Solutions as a go-to destination for aspiring React.js developers in the region. ... To demonstrate the basic usage of the Context API, let’s create a simple example where we manage a theme (light or dark) across multiple components. I have enrolled for Salesforce Admin and development online course at CRS info solutions. It’s really the best training i have ever taken and syllabus is highly professional
Rating: 5 ​
🌐
W3Schools
w3schools.com › react › react_usecontext.asp
React useContext Hook
Now, all components in this tree will have access to the user Context.
🌐
React
react.dev › learn › passing-data-deeply-with-context
Passing Data Deeply with Context – React
In this example, you specified 1 as the argument to createContext, so useContext(LevelContext) returns 1, setting all those headings to <h1>. Let’s fix this problem by having each Section provide its own context.
🌐
LogRocket
blog.logrocket.com › home › react context tutorial: complete guide with practical examples
React Context tutorial: Complete guide with practical examples - LogRocket Blog
February 19, 2025 - Instead of passing the addToast() function as a prop, Context has enabled the child components to trigger toast messages directly. This makes the approach scalable as you add more components to your app. This example demonstrates how React Context can be used to manage shared functionalities like toast messages.
🌐
React
react.dev › reference › react › useContext
useContext – React
Here, the context value is a JavaScript object with two properties, one of which is a function. Whenever MyApp re-renders (for example, on a route update), this will be a different object pointing at a different function, so React will also have to re-render all components deep in the tree that call useContext(AuthContext).
🌐
Medium
medium.com › @ankushchavan0411 › getting-started-with-react-context-api-dca142757080
Getting Started with React Context API | by Ankush S Chavan | Medium
January 8, 2024 - If you’re diving into React development and want to understand how to manage state efficiently, the React Context API is a powerful tool worth exploring. In this guide, we’ll take you through the basics of getting started with React Context API, accompanied by clear and concise code examples.
🌐
GeeksforGeeks
geeksforgeeks.org › reactjs › context-in-react
Context in React - GeeksforGeeks
Example: If we have three components in our app, A->B->C where A is the parent of B and B is the parent of C. To change a state from C and pass it to A, keep the state of A in a store, then extract the state from the store and use it in C. This ...
Published   July 15, 2025
🌐
Robin Wieruch
robinwieruch.de › react-context
How to use React Context
Generally speaking there are two use cases when to use it: When your React component hierarchy grows vertically in size and you want to be able to pass props to child components without bothering components in between.
🌐
freeCodeCamp
freecodecamp.org › news › react-context-api-explained-with-examples
React Context API Explained with Examples
May 30, 2024 - We will also look at common use ... at a basic example in which we have a ParentComponent that holds some count state, and you need to pass that state down to a deeply nested GrandchildComponent....
🌐
Medium
vonkunesnewton.medium.com › the-simplest-example-of-reacts-createcontext-and-usecontext-a92eedf2f87f
The simplest example of React’s createContext and useContext | by Ryan von Kunes Newton | Medium
January 7, 2024 - We can just create a context using createContext. ... Any components nested underneath the Provider can now access its value. ... We can use useContext to pull in the value without having to have passed it down through props.
🌐
freeCodeCamp
freecodecamp.org › news › react-context-for-beginners
React Context for Beginners – The Complete Guide (2021)
July 21, 2021 - This means that we can create and use context directly by importing React in any React project. ... Create context using the createContext method. Take your created context and wrap the context provider around your component tree. Put any value you like on your context provider using the value prop. Read that value within any component by using the context consumer. Does all this sound confusing? It's simpler than you think. Let's take a look at a very basic example.