Skip to content

Instantly share code, notes, and snippets.

@danilowoz
Last active January 14, 2020 13:49
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save danilowoz/5d0b3efa21a33186296febd49ce11802 to your computer and use it in GitHub Desktop.
Save danilowoz/5d0b3efa21a33186296febd49ce11802 to your computer and use it in GitHub Desktop.
Gist: React.Context<Class | Hooks>
import React from "react";
import Provider, { Consumer } from "./Context";
const App = () => (
<Provider>
<Consumer>
{({ count }) => {
return (
<div>
<span>{count}</span>
<br />
</div>
);
}}
</Consumer>
<div>
<div>
<Consumer>
{({ increment, decrement }) => {
return (
<div>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</div>
);
}}
</Consumer>
</div>
</div>
</Provider>
);
export default App;
import React, { Component } from "react";
const Context = React.createContext();
class Provider extends Component {
state = {
count: 0
};
increment = () => {
this.setState({
count: this.state.count + 1
});
};
decrement = () => {
this.setState({
count: this.state.count - 1
});
};
render() {
return (
<Context.Provider
value={{
count: this.state.count,
increment: this.increment,
decrement: this.decrement
}}
>
{this.props.children}
</Context.Provider>
);
}
}
const Consumer = Context.Consumer;
export { Consumer };
export default Provider;
import { Provider, Context } from "./context";
const Counter = () => {
const { count, increment, decrement } = React.useContext(Context);
return (
<div>
<h2>{count}</h2>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</div>
);
};
const App = () => {
return (
<Provider>
<Counter />
</Provider>
);
};
import React from "react";
export const Context = React.createContext({
count: 0,
increment: () => {},
decrement: () => {}
});
export const Provider = ({ children }) => {
const [count, setCount] = React.useState(0);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
return (
<Context.Provider
value={{
count,
increment,
decrement
}}
>
{children}
</Context.Provider>
);
};
@SivaCse
Copy link

SivaCse commented Feb 20, 2019

Thanks for the stuff brother.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment