Skip to content

Instantly share code, notes, and snippets.

@artalar
Created September 8, 2018 18:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artalar/83a4240c633c0fb6726271fdd1456970 to your computer and use it in GitHub Desktop.
Save artalar/83a4240c633c0fb6726271fdd1456970 to your computer and use it in GitHub Desktop.
Detailed explanation of the new React context
const store = {
observedBits: {
foo: 0b01,
bar: 0b10
},
state: {
foo: 1,
bar: 1,
},
update(cb) {
this.state = cb(this.state);
}
};
const StoreContext = React.createContext(
store.state,
(prev, next) => {
let result = 0;
// `foo` changed
if (prev.foo !== next.foo) {
result |= store.observedBits.foo;
}
// `bar` changed
if (prev.bar !== next.bar) {
result |= store.observedBits.bar;
}
return result;
}
);
const Foo = () => (
<StoreContext.Consumer unstable_observedBits={store.observedBits.foo}>
{({foo, update}) => ( // if `bar` changes, this code will not be executed
<button
onClick={() => update((state) => ({...state, foo: state.foo + 1}))}
>
increment "foo = {foo}"
</button>
)}
</StoreContext.Consumer>
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment