really minimal wrap on new React.createContext() to provide context with a set function for Consumer
NOTE
According to 0002-new-version-of-context, mutation is discouraged. But in some situations, Consumer really need a way to update the Provider. So, I come up with this module.
Usage
const Provider Consumer = <Provider defaultValue=1> <Consumer> { // ctx contain value and a set function return <button onClick= ctx> ctxvalue </button> } </Consumer></Provider>
ctx.set()
set function interface is similar to react component's setState(), which accept updater as object
or function
.
updater as function with the signature:
newValue
set will just replace the value. It will NOT merge newValue to prevValue.
keep value in your own state by Provider.onChange
you can also keep value in your own state (like Input)
const Provider Consumer = Component state = valueA: 1 { return <Provider value=thisstatevalueA onChange= this > ... </Provider> }
access via ctx.foo instead ctx.value.foo
Can use createStateMutext
to mutate whole provider state instead of a value field only.
const C = const App = <CProvider> <CConsumer> <button onClick= ctx > ctxfoo </button> </CConsumer> </CProvider>
createObservableMutext
Consumers can observe part of changes easily by names. Names are auto calculate to bitmask
const C = const App = <CProvider> <CConsumer // observe to foo and only render if foo is changed observe="foo" > `Foo: ` </CConsumer> <CConsumer // observe to bar and only render if bar is changed observe="bar" > `Bar: ` </CConsumer> <CConsumer // observe to bar OR foo and render if bar OR foo are changed observe="bar,foo" > `BarOrFoo: ` </CConsumer> </CProvider>
use option to add functions to ctx
createMutableContext signature:
const options = // init at the end of provider constructor {} // init at the end of consumer constructor {} // prepare ctx to pass to consumer children function ctx const C = const App = <CProvider> <CConsumer> <button // can call inc1 onClick=ctxinc1 > ctxvalue </button> </CConsumer> </CProvider>