0
0
ReactHow-ToBeginner · 3 min read

How to Provide Context Value in React: Simple Guide

In React, you provide a context value by wrapping your components with Context.Provider and passing the value via the value prop. This makes the value accessible to all nested components that consume the context.
📐

Syntax

To provide a context value, use Context.Provider and pass the data with the value prop. Wrap the components that need access inside this provider.

  • Context: The context object created by React.createContext().
  • Provider: A component that supplies the context value.
  • value: The data you want to share with child components.
jsx
const MyContext = React.createContext();

function App() {
  return (
    <MyContext.Provider value={{ user: 'Alice' }}>
      <ChildComponent />
    </MyContext.Provider>
  );
}
💻

Example

This example shows how to provide a user name via context and access it in a nested component.

jsx
import React, { createContext, useContext } from 'react';

const UserContext = createContext();

function App() {
  const user = { name: 'Alice' };

  return (
    <UserContext.Provider value={user}>
      <Profile />
    </UserContext.Provider>
  );
}

function Profile() {
  const user = useContext(UserContext);
  return <h1>Hello, {user.name}!</h1>;
}

export default App;
Output
Hello, Alice!
⚠️

Common Pitfalls

Common mistakes when providing context values include:

  • Not wrapping components with Provider, so consumers get undefined.
  • Passing a new object or function inline causing unnecessary re-renders.
  • Forgetting to import or use the correct context object.
jsx
/* Wrong: No Provider wrapping, consumer gets undefined */
const MyContext = React.createContext();

function Child() {
  const value = React.useContext(MyContext);
  return <div>{value}</div>; // value is undefined
}

/* Right: Wrap with Provider and pass value */
function App() {
  return (
    <MyContext.Provider value="Hello">
      <Child />
    </MyContext.Provider>
  );
}
📊

Quick Reference

Remember these key points when providing context values:

  • Always wrap consumers inside Context.Provider.
  • Pass stable values to avoid extra renders.
  • Use useContext hook to access the value inside functional components.

Key Takeaways

Wrap components with Context.Provider to provide context values.
Pass the shared data via the value prop on the provider.
Use useContext hook inside child components to consume the value.
Avoid passing new objects or functions inline to prevent unnecessary re-renders.
Always ensure consumers are inside the provider to get the context value.