Creating Context in React
Course: React JS Training
Topic: Creating Context using the Context API
Official Course: JustAcademy React JS Training
Course Demo: Register for React JS Course Demo
1. Introduction to Creating Context
Creating Context is the first step in using React's Context API to share data across multiple components. The createContext() function creates a context object that allows a parent component to provide information to descendant components without passing props through every intermediate component.
Context is useful when different components need access to common information, such as the logged-in user, theme settings, language preferences, or shopping cart data.
For example, if a website has a header, sidebar, dashboard, and profile section that all need the current user's information, you can create a UserContext and provide the user data through it.
2. What Is createContext()?
createContext() is a built-in React function imported from the react package. It creates a context object that can be used to provide and read a shared value.
Basic Syntax
import { createContext } from "react";
const MyContext = createContext(defaultValue);
Explanation:
createContext is the React function used to create a context.
MyContext is the context object that you create.
defaultValue is the fallback value used when no matching provider exists above the component reading the context.
The context is usually created outside React components so that the same context object can be imported and used by multiple files.
3. Why Do We Need to Create Context?
In a React application, components normally share information through props. When the data needs to pass through several intermediate components, the process is called prop drilling.
Example Without Context
function App() {
const userName = "Rahul";
return <Dashboard userName={userName} />;
}
function Dashboard({ userName }) {
return <Profile userName={userName} />;
}
function Profile({ userName }) {
return <Welcome userName={userName} />;
}
function Welcome({ userName }) {
return <h2>Welcome, {userName}!</h2>;
}
Here, Dashboard and Profile forward the userName prop even though they do not use it themselves.
Example With Context
By creating a context, the application can provide the user name once. A deeply nested component can then read that value using useContext(), without requiring every intermediate component to forward it.
4. Creating Your First Context
Let's create a simple context for sharing a website theme.
Step 1: Import createContext
import { createContext } from "react";
This statement imports the createContext() function from React.
Step 2: Create the Context Object
const ThemeContext = createContext("light");
In this example:
ThemeContext is the name of the context object.
"light" is the default context value.
- The default value is used only when there is no matching provider above the component consuming the context.
Step 3: Export the Context
import { createContext } from "react";
export const ThemeContext = createContext("light");
Exporting the context makes it available to other files that need to provide or read its value.
5. Understanding the Default Value
The default value is the fallback value supplied when you create a context. It does not act as automatically changing state.
Example 1: String Default Value
import { createContext } from "react";
export const ThemeContext = createContext("light");
If a component reads this context without a matching provider above it, the component receives "light".
Example 2: Number Default Value
import { createContext } from "react";
export const FontSizeContext = createContext(16);
The default font size is 16.
Example 3: Object Default Value
import { createContext } from "react";
export const UserContext = createContext({
name: "Guest",
role: "Visitor"
});
This context has an object as its default value.
Example 4: Null Default Value
import { createContext } from "react";
export const AuthContext = createContext(null);
Use null when there is no meaningful fallback value. Components consuming this context should handle the possibility that the value is null.
| Default Value |
Example |
Possible Use |
| String |
createContext("light") |
Theme or language label |
| Number |
createContext(16) |
Font size or numeric setting |
| Object |
createContext({ name: "Guest" }) |
User details or preferences |
| Array |
createContext([]) |
List of items |
| Null |
createContext(null) |
Value that has no meaningful fallback |
6. Creating Context in a Separate File
In a real React project, it is a good practice to create shared contexts in separate files. This helps keep the application organized and allows multiple components to use the same context object.
Suggested Project Structure
src/
├── context/
│ └── ThemeContext.jsx
├── components/
│ └── ThemeDisplay.jsx
├── App.jsx
└── main.jsx
ThemeContext.jsx
import { createContext } from "react";
export const ThemeContext = createContext("light");
This file creates and exports the context.
Why Use a Separate File?
- It makes context reusable across multiple components.
- It prevents repeated creation of separate context objects.
- It keeps shared application data organized.
- It makes importing and maintaining context easier.
7. Creating Different Contexts for Different Purposes
A React application can have multiple contexts. Each context can represent a different type of shared information.
Example: Theme, User, and Language Contexts
import { createContext } from "react";
export const ThemeContext = createContext("light");
export const UserContext = createContext(null);
export const LanguageContext = createContext("en");
Here, three independent contexts are created:
ThemeContext stores a theme value.
UserContext stores user information.
LanguageContext stores a language preference.
Keeping unrelated contexts separate can make the application easier to understand and maintain.
8. Providing a Value Through the Created Context
Creating a context does not automatically make a new value available to the component tree. A parent component must provide a value through that context.
React 19 and Later
import { ThemeContext } from "./context/ThemeContext";
function App() {
return (
<ThemeContext value="dark">
<h1>My React Application</h1>
</ThemeContext>
);
}
export default App;
React 18 and Earlier
import { ThemeContext } from "./context/ThemeContext";
function App() {
return (
<ThemeContext.Provider value="dark">
<h1>My React Application</h1>
</ThemeContext.Provider>
);
}
export default App;
Important: The value prop contains the value that descendant components will receive. If the provider is present but its value is explicitly undefined, React supplies undefined, not the context's default value.
9. Reading the Created Context with useContext()
After creating and providing a context, a functional component can read its value with the useContext() Hook.
ThemeContext.jsx
import { createContext } from "react";
export const ThemeContext = createContext("light");
ThemeDisplay.jsx
import { useContext } from "react";
import { ThemeContext } from "../context/ThemeContext";
function ThemeDisplay() {
const theme = useContext(ThemeContext);
return <p>Current theme: {theme}</p>;
}
export default ThemeDisplay;
App.jsx
import { ThemeContext } from "./context/ThemeContext";
import ThemeDisplay from "./components/ThemeDisplay";
function App() {
return (
<ThemeContext.Provider value="dark">
<ThemeDisplay />
</ThemeContext.Provider>
);
}
export default App;
Expected Output
Current theme: dark
The component displays dark because the provider supplies that value. The default value, light, is not used when a matching provider supplies a value.
10. Creating Context for User Information
Context is useful for sharing a user's name, role, or other non-sensitive display information throughout an application.
UserContext.jsx
import { createContext } from "react";
export const UserContext = createContext({
name: "Guest",
role: "Visitor"
});
App.jsx
import { UserContext } from "./context/UserContext";
import UserProfile from "./components/UserProfile";
function App() {
const user = {
name: "Rahul Sharma",
role: "Frontend Developer"
};
return (
<UserContext.Provider value={user}>
<UserProfile />
</UserContext.Provider>
);
}
export default App;
UserProfile.jsx
import { useContext } from "react";
import { UserContext } from "../context/UserContext";
function UserProfile() {
const user = useContext(UserContext);
return (
<section>
<h2>User Profile</h2>
<p>Name: {user.name}</p>
<p>Role: {user.role}</p>
</section>
);
}
export default UserProfile;
Expected Output
User Profile
Name: Rahul Sharma
Role: Frontend Developer
This example demonstrates how the context provides an object rather than a single string.
11. Creating Context with Dynamic Data
When the context value must change, combine the context with a state Hook such as useState(). The state belongs to a component, and the provider shares the current state value with descendant components.
Example: Dynamic Theme Context
import { createContext, useContext, useState } from "react";
const ThemeContext = createContext("light");
function ThemeDisplay() {
const theme = useContext(ThemeContext);
return <p>Selected theme: {theme}</p>;
}
function App() {
const [theme, setTheme] = useState("light");
function toggleTheme() {
setTheme(currentTheme =>
currentTheme === "light" ? "dark" : "light"
);
}
return (
<ThemeContext.Provider value={theme}>
<ThemeDisplay />
<button onClick={toggleTheme}>Change Theme</button>
</ThemeContext.Provider>
);
}
export default App;
When the button is clicked, the state changes. The provider receives the updated value, and components that read the context are updated accordingly.
12. Common Mistakes When Creating Context
| Mistake |
Explanation |
Solution |
| Creating context inside a component |
A new context object can be created during repeated renders. |
Create the context at module level, outside components. |
| Forgetting to export context |
Other files cannot import the context using the expected named export. |
Use a consistent named or default export. |
| Creating multiple context objects accidentally |
A provider and consumer may use different context instances. |
Import the same context object from one shared module. |
| Expecting the default value to change |
The default is a static fallback, not state. |
Use state and provide the changing value. |
| Forgetting the provider value |
A provider without a value may pass undefined. |
Set the correct value prop. |
| Using context for every value |
It can make simple component communication unnecessarily complicated. |
Use props for local parent-to-child communication. |
| Using an incorrect import path |
The application may fail to resolve the context module. |
Check the file location and relative import path. |
13. Best Practices for Creating Context
- Create contexts outside component functions.
- Use descriptive names such as
AuthContext, ThemeContext, or UserContext.
- Keep context definitions in separate files when they are shared by multiple components.
- Choose a meaningful default value, or use
null when no valid fallback exists.
- Ensure providers and consumers import the same context object.
- Keep unrelated state in separate contexts when that improves clarity and update behavior.
- Use
useContext() to read context in functional components.
- Combine context with state Hooks when the provided value needs to change.
- Remember that context is not a replacement for secure server-side authorization or secure credential storage.
14. Advantages of Creating Context
- Reduces the need for repeated prop passing.
- Makes shared data accessible to deeply nested components.
- Supports different data types, including strings, numbers, arrays, objects, and functions.
- Helps organize shared application values in dedicated modules.
- Works with React Hooks to support dynamic values.
- Is built into React and does not require an additional library.
15. Context API vs Props
| Feature |
Props |
Context API |
| Purpose |
Pass data between components explicitly. |
Share values with descendants through a provider. |
| Data passing |
Usually passed from parent to child. |
Read by descendants without forwarding through every level. |
| Best suited for |
Component-specific data and configuration. |
Shared values used across several components. |
| Setup |
Pass props directly. |
Create context and provide its value. |
| Dynamic values |
Can pass state and callbacks as props. |
Can distribute state and callbacks through context. |
16. Mini Practice Project: Create a Language Context
Objective: Create a context that shares a language preference with a child component.
Step 1: Create LanguageContext.jsx
import { createContext } from "react";
export const LanguageContext = createContext("English");
Step 2: Create LanguageDisplay.jsx
import { useContext } from "react";
import { LanguageContext } from "../context/LanguageContext";
function LanguageDisplay() {
const language = useContext(LanguageContext);
return <h2>Selected language: {language}</h2>;
}
export default LanguageDisplay;
Step 3: Update App.jsx
import { LanguageContext } from "./context/LanguageContext";
import LanguageDisplay from "./components/LanguageDisplay";
function App() {
return (
<LanguageContext.Provider value="Hindi">
<LanguageDisplay />
</LanguageContext.Provider>
);
}
export default App;
Expected Output
Selected language: Hindi
Learning Outcomes
- Create and export a context.
- Set a default context value.
- Provide a different value through a provider.
- Read the value using
useContext().
- Understand how context can reduce prop drilling.
17. Interview Questions and Answers
Q1. What is createContext() in React?
Answer: It is a React function that creates a context object for providing and reading values across a component tree.
Q2. How do you create a context?
Answer: Import createContext from React and call it outside a component, for example, const ThemeContext = createContext("light");.
Q3. What is the default value of a context?
Answer: It is the fallback value returned when no matching provider exists above the component reading the context.
Q4. Can a context contain an object?
Answer: Yes. Context can contain objects, arrays, strings, numbers, functions, and other JavaScript values.
Q5. Does creating a context automatically share its value?
Answer: No. A context must be used with a provider to supply a specific value to the component tree. Without a matching provider, the consumer receives the default value.
Q6. Where should createContext() be called?
Answer: It should generally be called outside React component functions, usually in a separate module.
Q7. Can we create more than one context?
Answer: Yes. An application can create separate contexts for theme, authentication, language, and other shared values.
Q8. What is the difference between creating context and providing context?
Answer: Creating context defines the context object. Providing context supplies a value to descendant components through a provider.
Q9. Is the default context value reactive?
Answer: No. The default value is static. To share changing data, use state and pass the current value to the provider.
Q10. Which Hook is commonly used to read context?
Answer: useContext() is commonly used by functional components to read a context value.
18. Practice Exercises
- Create a
ThemeContext with a default value of "light".
- Create a
UserContext with a default object containing a name and role.
- Create a
LanguageContext with a default value of "English".
- Export a context from one file and import it into two different components.
- Provide a different context value from the default and display it in a child component.
- Build a theme toggle using
createContext(), useContext(), and useState().
- Explain why creating a context inside a component is generally discouraged.
19. Quick Revision Checklist
- Understand the purpose of
createContext().
- Know the basic syntax for creating context.
- Understand how default values work.
- Know how to export and import a context object.
- Understand the difference between creating and providing context.
- Know how to read context using
useContext().
- Understand how state can make context values dynamic.
- Recognize common mistakes and follow context best practices.
20. Conclusion
Creating Context is the foundation of using React's Context API. The createContext() function defines a context object, while a provider supplies the value that descendant components can access using useContext(). Creating reusable contexts in separate files helps organize shared information and reduces unnecessary prop drilling in React applications.
To learn more, visit JustAcademy React JS Training or Register for React JS Course Demo.
21. Official React References