<MyContext.Consumer> {value => { }} </MyContext.Consumer> VS let value = useContext(MyContext);
What is the difference between this two snippets, using Context.Consumer and using useContext hook to access values passed by the context Provider? I think useContext will subscribe to the context Provider, since we passed the Context as an argument, so that it will trigger a re-render, when the provider value changes.
That is correct. They will do basically the same thing. In my opinion, the useContext hook has a much nicer and readable syntax. const value = useContext(MyContext); Accepts a context object (the value returned from React.
The function takes context as an argument and returns JSX which renders the data passed via context. In functional components on the other hand, useContext hook takes a context object (object returned by React. CreateContext ) as an argument and returns the object passed via value prop of Context. Provider .
To pass multiple values in React Context, we can use the Provider API. Also, we can easily consume the context data by utilizing the useContext React Hook. However, it is important to understand the basic syntax and approach behind this. To get a better idea, let us look at a simple example.
Context.Consumer Using this component lets you subscribe to a context within a function component. Requires a function as a child. The function receives the current context value and returns a React node.
That is correct. They will do basically the same thing.
In my opinion, the useContext
hook has a much nicer and readable syntax.
From React Docs:
https://reactjs.org/docs/hooks-reference.html#usecontext
useContext
const value = useContext(MyContext); Accepts a context object (the value returned from React.createContext) and returns the current context value for that context. The current context value is determined by the value prop of the nearest above the calling component in the tree.
When the nearest above the component updates, this Hook will trigger a rerender with the latest context value passed to that MyContext provider.
Also from React Docs:
https://reactjs.org/docs/context.html
Context.Consumer
<MyContext.Consumer> {value => /* render something based on the context value */} </MyContext.Consumer>
A React component that subscribes to context changes. This lets you subscribe to a context within a function component.
UPDATE:
From: http://brianyang.com/react-hooks-a-deeper-dive-featuring-usecontext-and-usereducer/
The new
useContext
hook to consume context does not change the concepts surrounding context, hence the plunge above. This context hook only gives us an extra, much prettier, way to consume context. It's amazingly helpful when applying it to components consuming multiple contexts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With