Created
September 8, 2018 18:24
-
-
Save artalar/83a4240c633c0fb6726271fdd1456970 to your computer and use it in GitHub Desktop.
Detailed explanation of the new React context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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