Ojasa Mirai

Ojasa Mirai

ReactJS

Loading...

Learning Level

๐ŸŸข Beginner๐Ÿ”ต Advanced
๐ŸŒ Context API Basics๐Ÿ“ฆ Creating Context๐Ÿ”Œ Context.Provider๐Ÿ” useContext Hook๐ŸŽฏ Passing Data with Context๐Ÿ”„ Context with useStateโšก Context Performance๐Ÿ—๏ธ Context Best Practices
Reactjs/Context/Creating Context

๐Ÿ“ฆ Creating Context โ€” Setting Up Your Context

Creating a Context is simple. You use `React.createContext()` to define what data your Context will hold. You can set initial values and even provide TypeScript types for safety.


๐ŸŽฏ Using createContext()

`createContext()` takes an initial value and returns a Context object. This Context object has two parts: a Provider (which supplies the data) and a Consumer (which receives it).

import { createContext } from "react";

// Basic context with initial value
const ThemeContext = createContext("light");

The initial value is what you get if you try to use the Context outside of a Provider (which you should avoid, but the initial value prevents crashes).

๐Ÿ’ก Context with TypeScript Types

For better type safety, define what your Context will contain:

import { createContext } from "react";

interface Theme {
  mode: "light" | "dark";
  primaryColor: string;
  fontSize: number;
}

// Create context with a type
const ThemeContext = createContext<Theme>({
  mode: "light",
  primaryColor: "#007bff",
  fontSize: 16,
});

// Now TypeScript knows what properties ThemeContext has
// and will warn you if you access something that doesn't exist

<details>

<summary>๐Ÿ“š More Examples</summary>

// Example 1: User context with methods
interface User {
  id: string;
  name: string;
  email: string;
}

interface UserContextType {
  user: User | null;
  isLoading: boolean;
}

const UserContext = createContext<UserContextType>({
  user: null,
  isLoading: false,
});

// Example 2: Context with functions
interface AuthContextType {
  isAuthenticated: boolean;
  login: (email: string, password: string) => Promise<void>;
  logout: () => void;
}

const AuthContext = createContext<AuthContextType>({
  isAuthenticated: false,
  login: async () => {},
  logout: () => {},
});

</details>

๐ŸŽจ Real-World Example: Creating a Language Context

Many apps support multiple languages. You can create a Context to manage the current language:

import { createContext } from "react";

type Language = "en" | "es" | "fr";

interface LanguageContextType {
  language: Language;
  messages: Record<string, string>;
}

const LanguageContext = createContext<LanguageContextType>({
  language: "en",
  messages: {
    greeting: "Hello",
    goodbye: "Goodbye",
  },
});

// You could also define message translations
const translations = {
  en: {
    greeting: "Hello",
    goodbye: "Goodbye",
  },
  es: {
    greeting: "Hola",
    goodbye: "Adiรณs",
  },
  fr: {
    greeting: "Bonjour",
    goodbye: "Au revoir",
  },
};

// Now you can use this context with a Provider
export { LanguageContext, translations };

๐Ÿ“Š Context Creation Patterns

PatternUse CaseExample
Simple valueSingle piece of data`createContext("light")`
Object valueRelated data together`createContext({ user, isLoading })`
With functionsData + actions`createContext({ state, setState })`
TypeScript typedType-safe access`createContext<MyType>(initialValue)`

๐Ÿ”‘ Key Takeaways

  • โœ… Use `createContext()` to create a new Context
  • โœ… Provide an initial value (helpful for defaults)
  • โœ… Use TypeScript to define what your Context contains
  • โœ… Context types make your code safer and provide better IDE support
  • โœ… The initial value is used if Context is accessed outside a Provider
  • โœ… A single Context can hold multiple related values
  • โœ… Name your Contexts clearly (e.g., `UserContext`, not `Context`)

Ready to practice? Challenges | Next: Context.Provider


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep โ€ข Build Real โ€ข Verify Skills โ€ข Launch Forward

Courses

PythonFastapiReactJSCloud

ยฉ 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn