Context.Consumer vs useContext() to access values passed by Context.Provider

Viewed 20329
<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.

1 Answers

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 <MyContext.Provider> above the calling component in the tree.

When the nearest <MyContext.Provider> 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/

From: https://testdriven.io/blog/react-hooks-advanced/

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.

Related