๐ŸŒ
React
react.dev โ€บ reference โ€บ react โ€บ createContext
createContext โ€“ React
React will also re-run this function ... information deep down without explicitly passing props. Call createContext outside any components to create one or more contexts....
๐ŸŒ
React TypeScript Cheatsheets
react-typescript-cheatsheet.netlify.app โ€บ context
Context | React TypeScript Cheatsheets
Call useContext to read and subscribe to the context. import { useContext } from "react"; const MyComponent = () => { const theme = useContext(ThemeContext); return <p>The current theme is {theme}.</p>; }; If you don't have any meaningful default ...
๐ŸŒ
React Router
reactrouter.com โ€บ api โ€บ utils โ€บ createContext
createContext | React Router
Otherwise, reading this context when no value has been set will throw an error. import { createContext } from "react-router"; // Create a context for user data export const userContext = createContext<User | null>(null); import { getUserFromSession } from "~/auth.server"; import { userContext ...
๐ŸŒ
React
legacy.reactjs.org โ€บ docs โ€บ context.html
Context โ€“ React
Creates a Context object. When React renders a component that subscribes to this Context object it will read the current context value from the closest matching Provider above it in the tree.
๐ŸŒ
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
๐ŸŒ
Devtrium
devtrium.com โ€บ posts โ€บ how-use-react-context-pro
How to use React Context like a pro - Devtrium
September 13, 2021 - In situations where you care about this (and only in those), you can separate your state and your state setters in two different contexts. I believe this idea was first introduced by Kent C. Dodds in this blog post. The implementation of that pattern is the following: ... import React, { createContext, useContext, useState, useEffect, useCallback } from "react"; // create contexts
๐ŸŒ
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.
๐ŸŒ
DEV Community
dev.to โ€บ diwakarkashyap โ€บ createcontext-in-react-important-for-interview-and-development-22d3
createContext in React? Important for Interview and Development - DEV Community
August 10, 2023 - createContext is a method provided by React's Context API that facilitates a way to pass data through the component tree without having to pass props down manually at every level.
๐ŸŒ
React
react.dev โ€บ learn โ€บ passing-data-deeply-with-context
Passing Data Deeply with Context โ€“ React
In general, if some information ... to the entire tree below it. ... Create and export it with export const MyContext = createContext(defaultValue)....
Find elsewhere
๐ŸŒ
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 a component that is used to wrap components in order to access to the context's value. This is where you pass the values that you want to share throughout the component tree using 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}> {children} {/*all components in its subtree*/} </MyContext.Provider> ); }; export default App;
๐ŸŒ
Peterkellner
peterkellner.net โ€บ 2023 โ€บ 05 โ€บ 11 โ€บ Creating-a-Custom-React-Context-Provider
Creating a Custom React Context Provider | Peter Kellner's Blog
2 weeks ago - In this component, weโ€™re accessing the cookies, the search value, and the function to set the search value from our context. Weโ€™re filtering the cookies based on the search value and rendering them in a list. Weโ€™re also creating an input field that sets the search value when itโ€™s changed. Finally, to see our CookieList component in action, letโ€™s import it into our index.tsx file: import React from 'react'; import CookieList from '../components/CookieList'; const Home: React.FC = () => ( <div> <h1>Welcome to the Cookie Shop!</h1> <CookieList /> </div> ); export default Home;
๐ŸŒ
Refine
refine.dev โ€บ home โ€บ blog โ€บ tutorials โ€บ a guide to usecontext and react context api
A Guide to useContext and React Context API | Refine
October 31, 2024 - You can use it to pass data from a parent component to its descendants without prop drilling. You can create a context by invoking the createContext function with an optional default value as in the example below.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ react-context-for-beginners
React Context for Beginners โ€“ The Complete Guide (2021)
July 21, 2021 - 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. In our App, let's pass down our own name using Context and read it in a nested component: User. import React from 'react'; export const UserContext = React.createContext(); export default function App() { return ( <UserContext.Provider value="Reed"> <User /> </UserContext.Provider> ) } function User() { return ( <UserContext.Consumer> {value => <h1>{value}</h1>} {/* prints: Reed */} </UserContext.Consumer> ) }
๐ŸŒ
npm
npmjs.com โ€บ package โ€บ create-react-context
create-react-context - npm
June 5, 2019 - Latest version: 0.3.0, last published: 7 years ago. Start using create-react-context in your project by running `npm i create-react-context`. There are 397 other projects in the npm registry using create-react-context.
      ยป npm install create-react-context
    
Published ย  Jun 05, 2019
Version ย  0.3.0
Author ย  James Kyle
๐ŸŒ
Fireship
fireship.dev โ€บ react-context
Guide to React Context - Fireship
React gives us the ability to do both of those things whenever we create a new Context using the React.createContext method. Typically, you create a new Context for each unique piece of data that needs to be available throughout your component tree.
๐ŸŒ
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 - It is quite handy when you have ... nested child component. Create a Context โ€” First, you create a Context using the createContext() function....
๐ŸŒ
Dmitri Pavlutin
dmitripavlutin.com โ€บ react-context-and-usecontext
A Guide to React Context and useContext() Hook
February 2, 2023 - Using the context in React requires 3 simple steps: creating the context, providing the context, and consuming the context.
Top answer
1 of 5
180

When there's no Provider, the defaultValue argument is used for the function createContext. This is helpful for testing components in isolation without wrapping them, or testing it with different values from the Provider.


Code sample:

Copyimport { createContext, useContext } from "react";

const Context = createContext( "Default Value" );

function Child() {
  const context = useContext(Context);
  return <h2>Child1: {context}</h2>;
}

function Child2() {
  const context = useContext(Context);
  return <h2>Child2: {context}</h2>;
}

function App() {

  return (
    <>
      <Context.Provider value={ "Initial Value" }>
        <Child /> {/* Child inside Provider will get "Initial Value" */}
      </Context.Provider>
        <Child2 /> {/* Child outside Provider will get "Default Value" */}
    </>
  );
}

Codesandbox Demo

2 of 5
58

Just sharing my typical setup when using TypeScript, to complete answer from @tiomno above, because I think many googlers that ends up here are actually looking for this:

Copyinterface GridItemContextType {
    /** Unique id of the item */
    i: string;
}
const GridItemContext = React.createContext<GridItemContextType | undefined>(
    undefined
);

export const useGridItemContext = () => {
    const gridItemContext = useContext(GridItemContext);
    if (!gridItemContext)
        throw new Error(
            'No GridItemContext.Provider found when calling useGridItemContext.'
        );
    return gridItemContext;
};

The hook provides a safer typing in this scenario. The undefined defaultValue protects you from forgetting to setup the provider.