Reputation: 724
I am trying to understand the React context API and was going through the official docs. I will appreciate if someone can throw some more light on the following points as the official doc does not address it clearly.
ContextProvider.js
import React from "react";
import {ContextConsumer} from "./ContextConsumer";
export const TestContext = React.createContext({
count: 1,
incrCount: (count)=>{
console.log(`count value :- ${count}`)
}
});
export class ContextProvider extends React.Component {
incrCount = () => {
this.setState({
count: this.state.count + 1,
});
};
state = {
count: 5,
incrCount: this.incrCount,
};
render() {
return (
<TestContext.Provider value={this.state}>
<ContextConsumer />
</TestContext.Provider>
);
}
}
ContextConsumer.js
import React from "react";
import { TestContext } from "./ContextProvider";
export class ContextConsumer extends React.Component {
static contextType=TestContext
componentDidMount() {
const {count,incrCount}= this.context;
console.log(`count:- ${(count)}`)
console.log(`incrCount:- ${incrCount}`)
}
render() {
return (
<div>
**// BELOW CODE IS WORKING AS EXPECTED**
<TestContext.Consumer>
{({ count, incrCount }) => (
<button onClick={incrCount}>Count is {count}</button>
)}
</TestContext.Consumer>
</div>
);
}
}
App.js
import {ContextProvider} from "../../playground/ContextProvider";
const output = (
<Provider store={reduxStore}>
<ContextProvider />
</Provider>
);
ReactDOM.render(output, document.getElementById("root"));
Upvotes: 3
Views: 6454
Reputation: 1
to put it more simply:
if (functional components) { useContext }
else {
if (multiple contexts) { Context.Consumer }
else { Class.contextType }
}
// "static contextType" is experimental lets avoid
Upvotes: 0
Reputation: 998
are almost same the difference between them is that (1) is used in class component and useContext is a hook and the best thing is we can use this hook multiple times in one functional component.(3) can only be used in jsx or in render(return).(1)and(2) can be used outside return.
Upvotes: 0
Reputation: 281686
What is the difference in contextType and Consumer methods to consume the values provided by Provider? In what situation we should use which method?
The static contextType
assignment was introduced in v16.6.0 as a way to use context outside of render method. The only difference between Consumer and static context is the fact that using contextType allows you use context outside of render method too
Can the value exposed by Provider in a class based component, be used by a react hook component using useContext?
Yes the context value from Provider can be used by useContext
too. However you can only make use of useContext
inside a functional component and not a class component and also after v16.8.0 or react which supports hooks
P.S. You must ensure one thing that you are not causing a circular dependency by importing provider in consumer component and also the other way around
Upvotes: 8