Creating Context in React JS
Creating Context in React JS is the process of creating a shared data container that allows components to access information without passing props manually through every intermediate component. React provides the createContext() function to create a context object. Context is commonly used for themes, user authentication, language preferences, and other shared application data.
Course: JustAcademy React JS Training Course
Course Demo: Register for React JS Course Demo
1. What Is Context in React?
Context is a React feature that allows data to be shared with multiple components in a component tree without explicitly passing that data through props at every level.
Normally, a parent component passes information to a child using props. If a deeply nested component needs the same information, every intermediate component may need to forward those props. This situation is known as prop drilling.
Context helps reduce prop drilling by making a value available to components inside a matching context provider.
Example of Prop Drilling
function App() {
const username = "Rahul";
return <Profile username={username} />;
}
function Profile({ username }) {
return <UserDetails username={username} />;
}
function UserDetails({ username }) {
return <h2>Welcome, {username}!</h2>;
}
In this example, the username prop passes through the Profile component even though that component only forwards the value.
Using Context Instead
With Context, a component can access the shared value directly using useContext(), provided it is inside the matching provider.
2. What Is createContext()?
createContext() is a React function used to create a context object. It accepts a default value and returns the context object that can later be used to provide and read shared data.
Syntax
import { createContext } from "react";
const MyContext = createContext(defaultValue);
Explanation
createContext: Creates a new context object.
MyContext: The variable that stores the created context.
defaultValue: The fallback value used when a component has no matching provider above it in the component tree.
The default value is static. It does not change automatically when application data changes. To provide changing values, combine Context with React state and a provider.
3. Importing createContext
Before creating a context, import createContext from React.
import { createContext } from "react";
You can create contexts for different kinds of shared information, such as a theme, user information, or language settings.
4. Creating Your First Context
Let's create a simple context that stores a default theme value.
Example: ThemeContext.js
import { createContext } from "react";
const ThemeContext = createContext("light");
export default ThemeContext;
Explanation
createContext("light") creates a context with "light" as its default value.
ThemeContext stores the context object.
export default ThemeContext makes the context available to other files.
At this stage, the context has been created, but no dynamic value has been supplied. A provider can supply the value that descendant components should receive.
5. Creating Context for Different Data Types
Context can hold different JavaScript values, including strings, numbers, objects, arrays, and functions.
Example 1: String Context
import { createContext } from "react";
export const ThemeContext = createContext("light");
Example 2: Number Context
import { createContext } from "react";
export const FontSizeContext = createContext(16);
Example 3: Object Context
import { createContext } from "react";
export const UserContext = createContext({
name: "Guest",
role: "Visitor"
});
Example 4: Context with a Null Default
import { createContext } from "react";
export const AuthContext = createContext(null);
Using null can be useful when there is no meaningful fallback value. In that case, components should handle the possibility that no provider is available.
6. Creating Context in a Separate File
In larger applications, it is good practice to create and export contexts from a separate file. This makes the context easier to import and reuse across multiple components.
Project Structure
src/
context/
ThemeContext.js
components/
Header.jsx
Profile.jsx
App.jsx
main.jsx
ThemeContext.js
import { createContext } from "react";
const ThemeContext = createContext("light");
export default ThemeContext;
Benefits
- Keeps shared context definitions organized.
- Allows multiple components to import the same context.
- Reduces duplicate context declarations.
- Makes application code easier to maintain.
7. Providing a Context Value
After creating a context, use its provider to make a value available to components inside it. In React 19 and later, you can render the context object directly as a provider. In older React versions, use .Provider.
React 19 and Later
<ThemeContext value="dark">
<Header />
</ThemeContext>
Older React Versions
<ThemeContext.Provider value="dark">
<Header />
</ThemeContext.Provider>
The value prop determines the value received by descendant components that read this context. The provider must be above the component that reads the context.
8. Complete Example: Creating and Using Theme Context
This example creates a context, supplies a theme value, and reads that value inside a child component.
Step 1: Create ThemeContext.js
import { createContext } from "react";
const ThemeContext = createContext("light");
export default ThemeContext;
Step 2: Create Header.jsx
import { useContext } from "react";
import ThemeContext from "../context/ThemeContext";
function Header() {
const theme = useContext(ThemeContext);
return (
<header>
<h2>Current Theme: {theme}</h2>
</header>
);
}
export default Header;
Step 3: Use the Provider in App.jsx
import ThemeContext from "./context/ThemeContext";
import Header from "./components/Header";
function App() {
return (
<ThemeContext value="dark">
<Header />
</ThemeContext>
);
}
export default App;
For React versions before React 19: Replace and its closing tag with and .
Output
Current Theme: dark
How it works: The context is created in ThemeContext.js. The App component provides the value "dark". The Header component reads that value through useContext(ThemeContext).
9. Creating Context with State
To make a context value change in response to user actions, combine Context with useState(). The state belongs to a component, and its current value is passed through the provider.
Example: Dynamic Theme Context
import { createContext, useContext, useState } from "react";
const ThemeContext = createContext("light");
function ThemeDisplay() {
const theme = useContext(ThemeContext);
return <h2>Current Theme: {theme}</h2>;
}
function App() {
const [theme, setTheme] = useState("light");
return (
<ThemeContext value={theme}>
<ThemeDisplay />
<button onClick={() => setTheme(
theme === "light" ? "dark" : "light"
)}>
Change Theme
</button>
</ThemeContext>
);
}
export default App;
When the button is clicked, the state changes and React updates the provider value. Components reading that context receive the updated value.
10. Default Value vs. Provider Value
| Feature |
Default Value |
Provider Value |
| Purpose |
Fallback when no matching provider exists above the component. |
Value supplied to descendants within the provider. |
| Example |
createContext("light") |
|
| Changes automatically? |
No. |
Can change when the supplied value changes. |
| Priority |
Used when there is no matching provider. |
Used when a matching provider is present. |
Important: If a provider exists and its value is undefined, consumers receive undefined; React does not substitute the context's default value.
11. Common Uses of Creating Context
- Theme management: Share light or dark theme settings.
- Authentication: Share the current user or login status.
- Language settings: Share the selected language throughout the application.
- Shopping cart: Share cart items and related actions with components.
- User preferences: Share settings such as font size or display options.
- Application configuration: Provide shared settings to nested components.
12. Best Practices for Creating Context
- Create contexts outside React components, usually at module level.
- Use clear names such as
ThemeContext, AuthContext, or LanguageContext.
- Export contexts from separate files when multiple components need them.
- Choose a meaningful default value, or use
null when no fallback makes sense.
- Remember that creating context does not itself provide a changing value; use a provider for that.
- Use
useContext() in function components to read context.
- Keep unrelated data in separate contexts when that makes the application easier to understand.
- Do not use Context for every value. Props are often simpler when data only needs to move between nearby components.
- Be mindful that components consuming a context re-render when its provided value changes.
13. Common Mistakes and Their Solutions
| Mistake |
Solution |
Forgetting to import createContext. |
Import it from react. |
| Creating a context inside a component unnecessarily. |
Declare the context outside the component. |
| Expecting the default value to update automatically. |
Use state and provide the current state value. |
| Reading a context outside its provider. |
Place the consumer component inside the matching provider or handle the fallback. |
Using a provider without the value prop. |
Pass the intended value using value={...}. |
| Using the wrong context object. |
Import and use the exact same context instance that the provider uses. |
| Using the old provider syntax in a React 19 example without understanding the version. |
Use the context object directly in React 19+, or .Provider in older versions. |
14. Difference Between createContext() and useContext()
| createContext() |
useContext() |
| Creates a context object. |
Reads the value of a context. |
| Usually called outside components. |
Called inside a function component or custom Hook. |
Example: createContext("light") |
Example: useContext(ThemeContext) |
| Defines the context and its fallback value. |
Returns the value from the closest matching provider above the consumer, or the default if no provider exists. |
15. Interview Questions and Answers
Q1. What is Context in React?
Context is a React feature for sharing data with descendant components without manually passing props through every intermediate component.
Q2. What is createContext()?
createContext() is a React function that creates a context object for providing and reading shared data.
Q3. What argument does createContext() accept?
It accepts a default value, which is used as a fallback when no matching provider exists above the consuming component.
Q4. Does creating a context automatically share a changing value?
No. You must provide a value through the context provider. For changing values, the provider can receive state from a component.
Q5. Can a context store an object?
Yes. Context can store strings, numbers, objects, arrays, functions, and other JavaScript values.
Q6. What is prop drilling?
Prop drilling is the process of passing props through multiple intermediate components to reach a deeply nested component.
Q7. Where should a context be created?
Usually outside React components in a separate module so that multiple components can import the same context.
Q8. What is the difference between a default value and a provider value?
The default value is a fallback when no matching provider exists. The provider value is supplied to descendants within the provider.
Q9. Which Hook is commonly used to read Context?
useContext() is the recommended Hook for reading context in function components.
Q10. When should Context be used?
Use Context when many components at different levels need access to the same information, such as a theme, authentication data, or language preferences.
16. Practice Exercises
- Create a
ThemeContext with "light" as its default value.
- Create a
UserContext with an object containing a name and role.
- Export a context from a separate file and import it into
App.jsx.
- Provide a context value to a child component using the correct provider syntax for your React version.
- Combine
createContext() with useState() to create a theme that can change when a button is clicked.
- Create a language context with
"English" as its default value.
17. Quick Revision Checklist
- Understand the purpose of React Context.
- Know the syntax of
createContext(defaultValue).
- Know how to import
createContext from React.
- Understand default values and provider values.
- Know how to export and import a context from another file.
- Understand the provider syntax difference between React 19+ and older versions.
- Know how Context helps reduce prop drilling.
- Understand how Context works with
useContext() and useState().
18. Conclusion
Creating Context is an important step in using React Context API. The createContext() function creates a reusable context object, while a provider makes a value available to descendant components. When combined with useContext() and state, Context helps organize shared application data and reduce unnecessary prop drilling.
For official reference, read the React createContext() documentation and the React useContext() documentation.
Learn React JS: JustAcademy React JS Training Course
Register for a Demo: Register for React JS Course Demo