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/Passing Data Context

🎯 Passing Data with Context — Sharing Complex Values

Context isn't limited to single values. You can pass objects, arrays, functions, and anything else your app needs to share across components.


🎯 Passing Objects through Context

Objects are the most common type of value to pass through Context. They let you group related data together:

import { createContext, useContext, useState } from "react";

interface User {
  id: string;
  name: string;
  email: string;
  role: "admin" | "user";
}

const UserContext = createContext<User | null>(null);

function App() {
  const [currentUser, setCurrentUser] = useState<User>({
    id: "1",
    name: "Alice",
    email: "alice@example.com",
    role: "admin",
  });

  return (
    <UserContext.Provider value={currentUser}>
      <Dashboard />
    </UserContext.Provider>
  );
}

function Dashboard() {
  const user = useContext(UserContext);

  return (
    <div>
      <h1>Welcome, {user?.name}</h1>
      <p>Role: {user?.role}</p>
    </div>
  );
}

💡 Passing Arrays through Context

Arrays are useful for sharing lists of items or multiple related values:

import { createContext, useContext, useState } from "react";

interface Todo {
  id: string;
  text: string;
  completed: boolean;
}

const TodoContext = createContext<Todo[]>([]);

function App() {
  const [todos, setTodos] = useState<Todo[]>([
    { id: "1", text: "Learn Context", completed: false },
    { id: "2", text: "Build an app", completed: false },
  ]);

  return (
    <TodoContext.Provider value={todos}>
      <TodoList />
    </TodoContext.Provider>
  );
}

function TodoList() {
  const todos = useContext(TodoContext);

  return (
    <ul>
      {todos.map((todo) => (
        <li key={todo.id}>{todo.text}</li>
      ))}
    </ul>
  );
}

<details>

<summary>📚 More Examples</summary>

// Example 1: Passing functions through Context
const NotificationContext = createContext({
  notify: (message: string) => {},
  clearNotifications: () => {},
});

function App() {
  const [notifications, setNotifications] = useState<string[]>([]);

  const notify = (message: string) => {
    setNotifications([...notifications, message]);
  };

  const clearNotifications = () => {
    setNotifications([]);
  };

  return (
    <NotificationContext.Provider
      value={{ notify, clearNotifications }}
    >
      <Content />
    </NotificationContext.Provider>
  );
}

function SuccessButton() {
  const { notify } = useContext(NotificationContext);

  return (
    <button onClick={() => notify("Success!")}>
      Show Success
    </button>
  );
}

// Example 2: Complex nested objects
const StoreContext = createContext({
  user: { id: "", name: "" },
  products: [],
  cart: [],
  settings: { theme: "", language: "" },
});

function App() {
  const value = {
    user: { id: "123", name: "Alice" },
    products: [
      { id: "1", name: "Widget", price: 19.99 },
    ],
    cart: [],
    settings: { theme: "dark", language: "en" },
  };

  return (
    <StoreContext.Provider value={value}>
      <Store />
    </StoreContext.Provider>
  );
}

</details>

🎨 Real-World Example: Sharing a List of Products

An e-commerce app might share products and cart data through Context:

import { createContext, useContext, useState } from "react";

interface Product {
  id: string;
  name: string;
  price: number;
  image: string;
}

interface CartItem extends Product {
  quantity: number;
}

const StoreContext = createContext({
  products: [] as Product[],
  cart: [] as CartItem[],
  addToCart: (product: Product) => {},
  removeFromCart: (productId: string) => {},
});

function App() {
  const [products] = useState<Product[]>([
    { id: "1", name: "Laptop", price: 999, image: "laptop.jpg" },
    { id: "2", name: "Mouse", price: 29, image: "mouse.jpg" },
  ]);

  const [cart, setCart] = useState<CartItem[]>([]);

  const addToCart = (product: Product) => {
    const existing = cart.find((item) => item.id === product.id);
    if (existing) {
      setCart(
        cart.map((item) =>
          item.id === product.id
            ? { ...item, quantity: item.quantity + 1 }
            : item
        )
      );
    } else {
      setCart([...cart, { ...product, quantity: 1 }]);
    }
  };

  const removeFromCart = (productId: string) => {
    setCart(cart.filter((item) => item.id !== productId));
  };

  const value = { products, cart, addToCart, removeFromCart };

  return (
    <StoreContext.Provider value={value}>
      <ProductCatalog />
      <ShoppingCart />
    </StoreContext.Provider>
  );
}

function ProductCatalog() {
  const { products, addToCart } = useContext(StoreContext);

  return (
    <div>
      {products.map((product) => (
        <div key={product.id}>
          <h3>{product.name}</h3>
          <p>${product.price}</p>
          <button onClick={() => addToCart(product)}>
            Add to Cart
          </button>
        </div>
      ))}
    </div>
  );
}

function ShoppingCart() {
  const { cart, removeFromCart } = useContext(StoreContext);

  return (
    <div>
      <h2>Cart ({cart.length} items)</h2>
      {cart.map((item) => (
        <div key={item.id}>
          <p>{item.name} x {item.quantity}</p>
          <button onClick={() => removeFromCart(item.id)}>
            Remove
          </button>
        </div>
      ))}
    </div>
  );
}

📊 Data Types to Pass Through Context

TypeUse CaseExample
StringSimple configTheme name, language code
ObjectRelated dataUser info, settings
ArrayLists of itemsProducts, notifications, todos
FunctionActions/callbacks`addToCart()`, `logout()`
BooleanFlags**`isLoading`, `isDarkMode`

🔑 Key Takeaways

  • ✅ Pass objects to group related data together
  • ✅ Arrays work great for lists of items
  • ✅ Include functions in Context to let components trigger actions
  • ✅ Context can hold any JavaScript value
  • ✅ Keep Context data organized with clear types
  • ✅ Avoid passing too many unrelated values in one Context
  • ✅ Spread complex objects in Context for easy access

Ready to practice? Challenges | Next: Context with useState


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