react-dividable-context

Demo available on GitHub Pages.
API
Similar to the official context API added in React 16.3, which is what gets used by this module internally.
type EqualsFunction<T> = (a: T, b: T) => boolean;
const context = create(defaultValue: T, EqualsFunction<T>);
const provider = <context.Provider/>;
const consumer = <context.Consumer/>;
const partialConsumer = context.getConsumer(['fieldA', 'fieldB']);
const listenToFieldA = <context.Consumer keys={['fieldA']} />;
const listenToSeveral = <partialConsumer keys={['fieldC']} />;
const listenForSubKey = <context.Consumer keys={['fieldA', ['fieldB', 'subA']]} />;
Important: Unlike the official Provider, the one exposed by context prevents its children from updating. This allows wrapping your app in the provider and updating the value
prop, without it having re-rendering the whole app. All (descendant) consumers will still update.
const context = create({});
<context.provider value={{}}>
<p>This will never update! {Date.now()}</p>
<context.consumer>
{data => <p>This one updates, though. {Date.now()}</p>}
</context.consumer>
</context.provider>
Usage
npm install --save react-dividable-context;
yarn add react-dividable-context;
import * as React from 'react';
import create from 'react-dividable-context';
interface ITest {
abc: string;
def: number;
idk: number[];
}
const contexter = create({ abc: 'ABC', def: 123, idk: [0] });
const ConsumerABC = contexter.getConsumer(['abc']);
const ConsumerMixed = contexter.getConsumer(['abc', 'def']);
interface IAppState {
test: ITest;
}
class App extends React.Component<any, IAppState> {
constructor(props: any, context?: any) {
super(props, context);
this.state = { test: { abc: 'ABC', def: 123, idk: [0] } };
}
public render() {
return (
<context.provider value={this.state.test}>
<context.consumer>
{test => <p>Something changed! {Date.now()}</p>}
</context.consumer>
<ConsumerABC>
{test => <p>Field 'abc' changed! {Date.now()}</p>}
</ConsumerABC>
<ConsumerMixed>
{test => <p>Field 'abc' and/or 'def' changed! {Date.now()}</p>}
</ConsumerMixed>
</context.provider>
)
}
}