Context.Consumer与useContext获取Provider传递值的差异是什么?
MyContext.Consumer and useContext Hook for Accessing Context Values Great question! Let's break down how these two approaches differ, plus confirm your understanding about context subscription.
Core Syntax & Usage Differences
1. <MyContext.Consumer> (Render Props Pattern)
This is the older, component-based way to access context values. It relies on the render props pattern—you pass a function as a child to the Consumer component, which receives the current context value as an argument.
Example:
<MyContext.Consumer> {value => ( <div>Current context value: {value}</div> )} </MyContext.Consumer>
Key notes:
- Works in both class components and function components (since it's a regular React component).
- Requires nesting in your JSX structure, which can get verbose if you need to access multiple contexts (you'd have to nest multiple Consumers).
2. useContext Hook
Introduced in React 16.8, this Hook simplifies context access for function components. You call it directly at the top level of your function component (or custom Hook) with the context object as an argument, and it returns the current context value.
Example:
import { useContext } from 'react'; function MyComponent() { const value = useContext(MyContext); return <div>Current context value: {value}</div>; }
Key notes:
- Only works in function components or custom Hooks (can't be used in class components).
- Has a much cleaner, flatter syntax—no need for nested JSX, and you can reuse the
valuevariable anywhere in your component. - To access multiple contexts, just call
useContextmultiple times (one per context).
Subscription & Re-rendering Behavior
Your understanding is 100% correct! Both approaches subscribe to the associated Context.Provider:
- When the Provider's
valueprop updates, all components using either<MyContext.Consumer>oruseContext(MyContext)will automatically re-render with the latest value. - Under the hood,
useContextis essentially a syntactic sugar for the Consumer component—it uses the same subscription logic to stay in sync with the Provider.
When to Use Which?
- Use
<MyContext.Consumer>if you're working with a class component, or if you need to access the context value only within a specific part of your JSX tree. - Use
useContextfor all function component scenarios—it's more concise and easier to maintain, especially when you need to use the context value in multiple places in the component.
内容的提问来源于stack exchange,提问作者Henok Tesfaye

