Skip to content

Instantly share code, notes, and snippets.

@shrynx
Last active May 10, 2018 01:01
Show Gist options
  • Save shrynx/5487d6acb8c2870238e65036a8b85a06 to your computer and use it in GitHub Desktop.
Save shrynx/5487d6acb8c2870238e65036a8b85a06 to your computer and use it in GitHub Desktop.
simple demo of react's context api
const CounterContext = React.createContext(0);
class CounterProvider extends React.Component {
state = { count: 0 };
incrementCount = () => {
this.setState(({ count }) => ({ count: count + 1 }));
};
componentDidMount() {
setInterval(this.incrementCount, 1000);
}
render() {
return (
<CounterContext.Provider value={this.state.count}>
{this.props.children}
</CounterContext.Provider>
);
}
}
const DisplayCount = () => (
<CounterContext.Consumer>
{value => <div>{value}</div>}
</CounterContext.Consumer>
);
class App extends React.Component {
render() {
return (
<CounterProvider>
<div>
<DisplayCount />
</div>
</CounterProvider>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment