Skip to content

Instantly share code, notes, and snippets.

@dkwingsmt
Last active April 26, 2018 00:03
Show Gist options
  • Select an option

  • Save dkwingsmt/1088c292f0056ad756ef71ac5dde7475 to your computer and use it in GitHub Desktop.

Select an option

Save dkwingsmt/1088c292f0056ad756ef71ac5dde7475 to your computer and use it in GitHub Desktop.
New react context penetrating shouldComponentUpdate?
import React, { Component, createContext } from 'react';
const ApplicationContext = createContext();
const { Provider, Consumer } = ApplicationContext;
class Display extends Component {
render() {
console.warn('Display render')
return (
<div>
<div>
Month: {this.props.month}
</div>
<div>
Day: {this.props.day}
</div>
</div>
)
}
}
class WrappedDisplay extends Component {
render() {
console.warn('WrappedDisplay render')
return (
<Consumer>
{context => (
<Display
{...context}
/>
)}
</Consumer>
)
}
}
class Container extends Component {
shouldComponentUpdate(nextProps) {
return this.props.month !== nextProps.month;
}
render() {
console.warn('Container render')
return <WrappedDisplay />;
}
}
class App extends Component {
state = {
month: 1,
day: 1,
}
render() {
return (
<div>
<div>
<button onClick={() => this.setState(({month}) => ({month: month+1}))}>
+ Month {this.state.month}
</button>
<button onClick={() => this.setState(({day}) => ({day: day+1}))}>
+ Day {this.state.day}
</button>
</div>
<Provider value={this.state}>
<Container
month={this.state.month}
/>
</Provider>
</div>
);
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment