@webkrafters/react-observable-context 2.1.1 → 2.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +287 -267
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1,267 +1,287 @@
1
- # React-Observable-Context
2
-
3
- A context bearing an observable consumer store. State changes within the store's internal state are only broadcasted to components subscribed to the store. In this way, the `React-Observable-Context` prevents repeated automatic re-renderings of entire component trees resulting from ***context*** state changes.
4
-
5
- **React::memo** *(and PureComponents)* remain the go-to solution for the repeated automatic re-renderings of entire component trees resulting from ***component*** state changes.
6
-
7
- _**Recommendation:**_ Wrap all components calling this package's ***useContext*** function in **React::memo**. This will protect such component and its descendants from unrelated cascading render operations.
8
-
9
- <h4><u>Install</u></h4>
10
-
11
- npm i -S @webkrafters/react-observable-context
12
-
13
- npm install --save @webkrafters/react-observable-context
14
-
15
- ## API
16
-
17
- The React-Observable-Context package exports **3** modules namely: the **createContext** method, the **useContext** hook and the **Provider** component.
18
-
19
- * **createContext** is a zero-parameter funtion returning a store-bearing context. Pass the context to the React::useContext() parameter to obtain the context's `store`.
20
-
21
- * **useContext** is analogous to React::useContext hook but returns the context store and takes a second parameter named ***watchedKeys***. The `watchedKeys` parameter is a list of state object property paths to watch. A change in any of the referenced properties automatically triggers a render of the component calling this hook.
22
-
23
- * **Provider** can immediately be used as-is anywhere the React-Observable-Context is required. It accepts **3** props and the customary Provider `children` prop. Supply the context to its `context` prop; the initial state to the customary Provider `value` prop; and the optional `prehooks` prop <i>(discussed in the prehooks section below)</i>.
24
-
25
- ***<u>Note:</u>*** the Provider `context` prop is not updateable. Once set, all further updates to this prop are not recorded.
26
-
27
- ### The Store
28
-
29
- The context's `store` exposes **4** methods for interacting with the context's internal state namely:
30
-
31
- * **getState**: (selector?: (state: State) => any) => any
32
-
33
- * **resetState**: VoidFunction // resets the state to the Provider initial `value` prop.
34
-
35
- * **setState**: (changes: PartialState\<State\>) => void // sets only new/changed top level properties.
36
-
37
- * **subscribe**: (listener: (newValue: PartialState\<State\>, oldValue: PartialState\<State\>) => void) => ***UnsubscribeFunction***
38
-
39
- ### Prehooks
40
-
41
- The context's store update operation adheres to **2** user supplied prehooks when present. Otherwise, the update operation proceeds normally to completion. They are named **resetState** and **setState** after the store update methods which utilize them.
42
-
43
- * **resetState**: (state: {current: State, original: State}) => boolean
44
-
45
- * **setState**: (newChanges: PartialState\<State\>) => boolean
46
-
47
- ***<u>Use case:</u>*** prehooks provide a central place for sanitizing, modifying, transforming, validating etc. all related incoming state updates. The prehook returns a **boolean** value (`true` to continue AND `false` to abort the update operation). The prehook may mutate (i.e. sanitize, transform, transpose) its argument values to accurately reflect the intended update value.
48
-
49
- ## Usage
50
-
51
- <i><u>context.js</u></i>
52
-
53
- import { createContext } from '@webkrafters/react-observable-context';
54
- const ObservableContext = createContext();
55
- export default ObservableContext;
56
-
57
- <i><u>reset.js</u></i>
58
-
59
- import React, { memo, useEffect } from 'react';
60
- import { useContext } from '@webkrafters/react-observable-context';
61
- import ObservableContext from './context';
62
- const Reset = memo(() => {
63
- const { resetState } = useContext( ObservableContext );
64
- useEffect(() => console.log( 'Reset component rendered.....' ));
65
- return ( <button onClick={ resetState }>reset context</button> );
66
- });
67
- Reset.displayName = 'Reset';
68
- export default Reset;
69
-
70
- <i><u>tally-display.js</u></i>
71
-
72
- import React, { memo, useEffect } from 'react';
73
- import { useContext } from '@webkrafters/react-observable-context';
74
- import ObservableContext from './context';
75
- import Reset from './reset';
76
- const CONTEXT_KEYS = [ 'color', 'price', 'type' ];
77
- const TallyDisplay = memo(() => {
78
- const { getState } = useContext( ObservableContext, CONTEXT_KEYS );
79
- useEffect(() => console.log( 'TallyDisplay component rendered.....' ));
80
- return (
81
- <div>
82
- <table>
83
- <tbody>
84
- <tr><td><label>Type:</label></td><td>{ getState( s => s.type ) }</td></tr>
85
- <tr><td><label>Color:</label></td><td>{ getState( s => s.color ) }</td></tr>
86
- <tr><td><label>Price:</label></td><td>{ getState( s => s.price ).toFixed( 2 ) }</td></tr>
87
- </tbody>
88
- </table>
89
- <div style={{ textAlign: 'right' }}>
90
- <Reset />
91
- </div>
92
- </div>
93
- );
94
- });
95
- TallyDisplay.displayName = 'TallyDisplay';
96
- export default TallyDisplay;
97
-
98
- <i><u>editor.js</u></i>
99
-
100
- import React, { memo, useCallback, useEffect, useRef } from 'react';
101
- import { useContext } from '@webkrafters/react-observable-context';
102
- import ObservableContext from './context';
103
- const Editor = memo(() => {
104
- const { setState } = useContext( ObservableContext );
105
- const priceInputRef = useRef();
106
- const colorInputRef = useRef();
107
- const typeInputRef = useRef();
108
- const updatePrice = useCallback(() => {
109
- setState({ price: Number( priceInputRef.current.value ) });
110
- }, []);
111
- const updateColor = useCallback(() => {
112
- setState({ color: colorInputRef.current.value });
113
- }, []);
114
- const updateType = useCallback(() => {
115
- setState({ type: typeInputRef.current.value });
116
- }, []);
117
- useEffect(() => console.log( 'Editor component rendered.....' ));
118
- return (
119
- <fieldset style={{ margin: '10px 0' }}>
120
- <legend>Editor</legend>
121
- <div style={{ margin: '10px 0' }}>
122
- <label>New Price: <input ref={ priceInputRef } /></label>
123
- { ' ' }
124
- <button onClick={ updatePrice }>update price</button>
125
- </div>
126
- <div style={{ margin: '10px 0' }}>
127
- <label>New Color: <input ref={ colorInputRef } /></label>
128
- { ' ' }
129
- <button onClick={ updateColor }>update color</button>
130
- </div>
131
- <div style={{ margin: '10px 0' }}>
132
- <label>New Type: <input ref={ typeInputRef } /></label>
133
- { ' ' }
134
- <button onClick={ updateType }>update type</button>
135
- </div>
136
- </fieldset>
137
- );
138
- });
139
- Editor.displayName = 'Editor';
140
- export default Editor;
141
-
142
- <i><u>product-description.js</u></i>
143
-
144
- import React, { memo, useEffect } from 'react';
145
- import { useContext } from '@webkrafters/react-observable-context';
146
- import ObservableContext from './context';
147
- const CONTEXT_KEYS = [ 'color', 'type' ];
148
- const ProductDescription = memo(() => {
149
- const store = useContext( ObservableContext, CONTEXT_KEYS );
150
- useEffect(() => console.log( 'ProductDescription component rendered.....' ));
151
- const color = store.getState( s => s.color );
152
- const type = store.getState( s => s.type );
153
- return (
154
- <div style={{ fontSize: 24 }}>
155
- <strong>Description:</strong> { color } { type }
156
- </div>
157
- );
158
- });
159
- ProductDescription.displayName = 'ProductDescription';
160
- export default ProductDescription;
161
-
162
- <i><u>price-sticker.js</u></i>
163
-
164
- import React, { memo, useEffect } from 'react';
165
- import { useContext } from '@webkrafters/react-observable-context';
166
- import ObservableContext from './context';
167
- const CONTEXT_KEYS = [ 'price' ];
168
- const PriceSticker = memo(() => {
169
- const { getState } = useContext( ObservableContext, CONTEXT_KEYS );
170
- useEffect(() => console.log( 'PriceSticker component rendered.....' ));
171
- return (
172
- <div style={{ fontSize: 36, fontWeight: 800 }}>
173
- ${ getState( s => s.price ).toFixed( 2 ) }
174
- </div>
175
- );
176
- });
177
- PriceSticker.displayName = 'PriceSticker';
178
- export default PriceSticker;
179
-
180
- <i><u>product.js</u></i>
181
-
182
- import React, { useCallback, useEffect, useState } from 'react';
183
- import { Provider } from '@webkrafters/react-observable-context';
184
- import ObservableContext from './context';
185
- import Editor from './editor';
186
- import PriceSticker from './price-sticker';
187
- import ProductDescription from './product-description';
188
- import TallyDisplay from './tally-display';
189
- const Product = ({ prehooks = undefined, type }) => {
190
- const [ state, setState ] = useState(() => ({
191
- color: 'Burgundy',
192
- price: 22.5,
193
- type
194
- }));
195
- useEffect(() => {
196
- setState({ type }); // use this to update only the changed state
197
- // setState({ ...state, type }); // this will reset the context internal state
198
- }, [ type ]);
199
- const overridePricing = useCallback( e => setState({ price: Number( e.target.value ) }), [] );
200
- return (
201
- <div>
202
- <div style={{ marginBottom: 10 }}>
203
- <label>$ <input onKeyUp={ overridePricing } placeholder="override price here..."/></label>
204
- </div>
205
- <Provider
206
- context={ ObservableContext }
207
- prehooks={ prehooks }
208
- value={ state }
209
- >
210
- <div style={{
211
- borderBottom: '1px solid #333',
212
- marginBottom: 10,
213
- paddingBottom: 5
214
- }}>
215
- <Editor />
216
- <TallyDisplay />
217
- </div>
218
- <ProductDescription />
219
- <PriceSticker />
220
- </Provider>
221
- </div>
222
- );
223
- };
224
- Product.displayName = 'Product';
225
- export default Product;
226
-
227
- <i><u>app.js</u></i>
228
-
229
- import React, { useCallback, useMemo, useState } from 'react';
230
- import Product from './product';
231
- const prehooks = {
232
- resetState: ( ...args ) => {
233
- console.log( 'resetting state with >>>> ', JSON.stringify( args ) );
234
- return true;
235
- },
236
- setState: ( ...args ) => {
237
- console.log( 'setting state with >>>> ', JSON.stringify( args ) );
238
- return true;
239
- }
240
- };
241
- const App = () => {
242
- const [ productType, setProductType ] = useState( 'Calculator' );
243
- const updateType = useCallback( e => setProductType( e.target.value ), [] );
244
- return (
245
- <div className="App">
246
- <h1>Demo</h1>
247
- <h2>A contrived product app.</h2>
248
- <div style={{ marginBottom: 10 }}>
249
- <label>Type: <input onKeyUp={ updateType } placeholder="override product type here..." /></label>
250
- </div>
251
- <Product prehooks={ prehooks } type={ productType } />
252
- </div>
253
- );
254
- };
255
- App.displayName = 'App';
256
- export default App;
257
-
258
- <i><u>index.js</i></b>
259
-
260
- import React from 'react';
261
- import ReactDOM from 'react-dom';
262
- import App from './app';
263
- ReactDOM.render(<App />, document.getElementById('root'));
264
-
265
- ## License
266
-
267
- MIT
1
+ # React-Observable-Context
2
+
3
+ A context bearing an observable consumer store. State changes within the store's internal state are only broadcasted to components subscribed to the store. In this way, the `React-Observable-Context` prevents repeated automatic re-renderings of entire component trees resulting from ***context*** state changes.
4
+
5
+ **React::memo** *(and PureComponents)* remain the go-to solution for the repeated automatic re-renderings of entire component trees resulting from ***component*** state changes.
6
+
7
+ _**Recommendation:**_ Wrap all components calling this package's ***useContext*** function in **React::memo**. This will protect such components and their descendants from unrelated cascading render operations.
8
+
9
+ <hr />
10
+
11
+ <h4><u>Install</u></h4>
12
+
13
+ npm i -S @webkrafters/react-observable-context
14
+
15
+ npm install --save @webkrafters/react-observable-context
16
+
17
+ ## API
18
+
19
+ The React-Observable-Context package exports **3** modules namely: the **createContext** method, the **useContext** hook and the **Provider** component.
20
+
21
+ * **createContext** is a zero-parameter funtion returning a store-bearing context. Pass the context to the React::useContext() parameter to obtain the context's `store`.
22
+
23
+ * **useContext** is analogous to React::useContext hook but returns the context store and takes a second parameter named ***watchedKeys***. The `watchedKeys` parameter is a list of state object property paths to watch. A change in any of the referenced properties automatically triggers a render of the component calling this hook.
24
+
25
+ * **Provider** can immediately be used as-is anywhere the React-Observable-Context is required. It accepts **3** props and the customary Provider `children` prop. Supply the context to its `context` prop; the initial state to the customary Provider `value` prop; and the optional `prehooks` prop <i>(discussed in the prehooks section below)</i>.
26
+
27
+ ***<u>Note:</u>*** the Provider `context` prop is not updateable. Once set, all further updates to this prop are not recorded.
28
+
29
+ ### The Store
30
+
31
+ The context's `store` exposes **4** methods for interacting with the context's internal state namely:
32
+
33
+ * **getState**: (selector?: (state: State) => any) => any
34
+
35
+ * **resetState**: VoidFunction // resets the state to the Provider initial `value` prop.
36
+
37
+ * **setState**: (changes: PartialState\<State\>) => void // sets only new/changed top level properties.
38
+
39
+ * **subscribe**: (listener: (newValue: PartialState\<State\>, oldValue: PartialState\<State\>) => void) => ***UnsubscribeFunction***
40
+
41
+ ### Prehooks
42
+
43
+ The context's store update operation adheres to **2** user supplied prehooks when present. Otherwise, the update operation proceeds normally to completion. They are named **resetState** and **setState** after the store update methods which utilize them.
44
+
45
+ * **resetState**: (state: {current: State, original: State}) => boolean
46
+
47
+ * **setState**: (newChanges: PartialState\<State\>) => boolean
48
+
49
+ ***<u>Use case:</u>*** prehooks provide a central place for sanitizing, modifying, transforming, validating etc. all related incoming state updates. The prehook returns a **boolean** value (`true` to continue AND `false` to abort the update operation). The prehook may mutate (i.e. sanitize, transform, transpose) its argument values to accurately reflect the intended update value.
50
+
51
+ ## Usage
52
+
53
+ <i><u>context.js</u></i>
54
+
55
+ import React from 'react';
56
+
57
+ import {
58
+ createContext,
59
+ Provider,
60
+ useContext
61
+ } from '@webkrafters/react-observable-context';
62
+
63
+ export const ObservableContext = createContext();
64
+
65
+ export const ObservableContextProvider = ({ children, prehooks, value }) => (
66
+ <Provider
67
+ context={ ObservableContext }
68
+ prehooks={ prehooks }
69
+ value={ value }
70
+ >
71
+ { children }
72
+ </Provider>
73
+ );
74
+ ObservableContextProvider.displayName = 'ObservableContextProvider';
75
+
76
+ export const useObservableContext = watchedKeys => useContext( ObservableContext, watchedKeys );
77
+
78
+ export default ObservableContext;
79
+
80
+ <i><u>index.js</i></b>
81
+
82
+ import React from 'react';
83
+ import ReactDOM from 'react-dom';
84
+ import App from './app';
85
+ ReactDOM.render(<App />, document.getElementById('root'));
86
+
87
+ <i><u>app.js</u></i>
88
+
89
+ import React, { useCallback, useState } from 'react';
90
+ import Product from './product';
91
+ const productUpdateHooks = {
92
+ resetState: ( ...args ) => {
93
+ console.log( 'resetting state with >>>> ', JSON.stringify( args ) );
94
+ return true;
95
+ },
96
+ setState: ( ...args ) => {
97
+ console.log( 'setting state with >>>> ', JSON.stringify( args ) );
98
+ return true;
99
+ }
100
+ };
101
+ const App = () => {
102
+ const [ productType, setProductType ] = useState( 'Calculator' );
103
+ const updateType = useCallback( e => setProductType( e.target.value ), [] );
104
+ return (
105
+ <div className="App">
106
+ <h1>Demo</h1>
107
+ <h2>A contrived product app.</h2>
108
+ <div style={{ marginBottom: 10 }}>
109
+ <label>Type: <input onKeyUp={ updateType } placeholder="override product type here..." /></label>
110
+ </div>
111
+ <Product
112
+ type={ productType }
113
+ updateHooks={ productUpdateHooks }
114
+ />
115
+ </div>
116
+ );
117
+ };
118
+ App.displayName = 'App';
119
+ export default App;
120
+
121
+ <i><u>product.js</u></i>
122
+
123
+ import React, { useCallback, useEffect, useState } from 'react';
124
+ import { ObservableContextProvider } from './context';
125
+ import Editor from './editor';
126
+ import PriceSticker from './price-sticker';
127
+ import ProductDescription from './product-description';
128
+ import TallyDisplay from './tally-display';
129
+ const Product = ({ type, updateHooks }) => {
130
+ const [ state, setState ] = useState(() => ({
131
+ color: 'Burgundy',
132
+ price: 22.5,
133
+ type
134
+ }));
135
+ useEffect(() => {
136
+ setState({ type }); // use this to update only the changed state value
137
+ // setState({ ...state, type }); // this will override the context internal state for these values
138
+ }, [ type ]);
139
+ const overridePricing = useCallback( e => setState({ price: Number( e.target.value ) }), [] );
140
+ return (
141
+ <div>
142
+ <div style={{ marginBottom: 10 }}>
143
+ <label>$ <input onKeyUp={ overridePricing } placeholder="override price here..." /></label>
144
+ </div>
145
+ <ObservableContextProvider
146
+ prehooks={ updateHooks }
147
+ value={ state }
148
+ >
149
+ <div style={{
150
+ borderBottom: '1px solid #333',
151
+ marginBottom: 10,
152
+ paddingBottom: 5
153
+ }}>
154
+ <Editor />
155
+ <TallyDisplay />
156
+ </div>
157
+ <ProductDescription />
158
+ <PriceSticker />
159
+ </ObservableContextProvider>
160
+ </div>
161
+ );
162
+ };
163
+ Product.displayName = 'Product';
164
+ export default Product;
165
+
166
+ <i><u>editor.js</u></i>
167
+
168
+ import React, { memo, useCallback, useEffect, useRef } from 'react';
169
+ import { useObservableContext } from './context';
170
+ const Editor = memo(() => {
171
+ const { setState } = useObservableContext();
172
+ const priceInputRef = useRef();
173
+ const colorInputRef = useRef();
174
+ const typeInputRef = useRef();
175
+ const updatePrice = useCallback(() => {
176
+ setState({ price: Number( priceInputRef.current.value ) });
177
+ }, []);
178
+ const updateColor = useCallback(() => {
179
+ setState({ color: colorInputRef.current.value });
180
+ }, []);
181
+ const updateType = useCallback(() => {
182
+ setState({ type: typeInputRef.current.value });
183
+ }, []);
184
+ useEffect(() => console.log( 'Editor component rendered.....' ));
185
+ return (
186
+ <fieldset style={{ margin: '10px 0' }}>
187
+ <legend>Editor</legend>
188
+ <div style={{ margin: '10px 0' }}>
189
+ <label>New Price: <input ref={ priceInputRef } /></label>
190
+ { ' ' }
191
+ <button onClick={ updatePrice }>update price</button>
192
+ </div>
193
+ <div style={{ margin: '10px 0' }}>
194
+ <label>New Color: <input ref={ colorInputRef } /></label>
195
+ { ' ' }
196
+ <button onClick={ updateColor }>update color</button>
197
+ </div>
198
+ <div style={{ margin: '10px 0' }}>
199
+ <label>New Type: <input ref={ typeInputRef } /></label>
200
+ { ' ' }
201
+ <button onClick={ updateType }>update type</button>
202
+ </div>
203
+ </fieldset>
204
+ );
205
+ });
206
+ Editor.displayName = 'Editor';
207
+ export default Editor;
208
+
209
+ <i><u>price-sticker.js</u></i>
210
+
211
+ import React, { memo, useEffect } from 'react';
212
+ import { useObservableContext } from './context';
213
+ const CONTEXT_KEYS = [ 'price' ];
214
+ const PriceSticker = memo(() => {
215
+ const { getState } = useObservableContext( CONTEXT_KEYS );
216
+ useEffect(() => console.log( 'PriceSticker component rendered.....' ));
217
+ return (
218
+ <div style={{ fontSize: 36, fontWeight: 800 }}>
219
+ ${ getState( s => s.price ).toFixed( 2 ) }
220
+ </div>
221
+ );
222
+ });
223
+ PriceSticker.displayName = 'PriceSticker';
224
+ export default PriceSticker;
225
+
226
+ <i><u>product-description.js</u></i>
227
+
228
+ import React, { memo, useEffect } from 'react';
229
+ import { useObservableContext } from './context';
230
+ const CONTEXT_KEYS = [ 'color', 'type' ];
231
+ const ProductDescription = memo(() => {
232
+ const store = useObservableContext( CONTEXT_KEYS );
233
+ useEffect(() => console.log( 'ProductDescription component rendered.....' ));
234
+ const color = store.getState( s => s.color );
235
+ const type = store.getState( s => s.type );
236
+ return (
237
+ <div style={{ fontSize: 24 }}>
238
+ <strong>Description:</strong> { color } { type }
239
+ </div>
240
+ );
241
+ });
242
+ ProductDescription.displayName = 'ProductDescription';
243
+ export default ProductDescription;
244
+
245
+ <i><u>tally-display.js</u></i>
246
+
247
+ import React, { memo, useEffect } from 'react';
248
+ import { useObservableContext } from './context';
249
+ import Reset from './reset';
250
+ const CONTEXT_KEYS = [ 'color', 'price', 'type' ];
251
+ const TallyDisplay = memo(() => {
252
+ const { getState } = useObservableContext( CONTEXT_KEYS );
253
+ useEffect(() => console.log( 'TallyDisplay component rendered.....' ));
254
+ return (
255
+ <div>
256
+ <table>
257
+ <tbody>
258
+ <tr><td><label>Type:</label></td><td>{ getState( s => s.type ) }</td></tr>
259
+ <tr><td><label>Color:</label></td><td>{ getState( s => s.color ) }</td></tr>
260
+ <tr><td><label>Price:</label></td><td>{ getState( s => s.price ).toFixed( 2 ) }</td></tr>
261
+ </tbody>
262
+ </table>
263
+ <div style={{ textAlign: 'right' }}>
264
+ <Reset />
265
+ </div>
266
+ </div>
267
+ );
268
+ });
269
+ TallyDisplay.displayName = 'TallyDisplay';
270
+ export default TallyDisplay;
271
+
272
+ <i><u>reset.js</u></i>
273
+
274
+ import React, { memo, useEffect } from 'react';
275
+ import { useObservableContext } from './context';
276
+ const Reset = memo(() => {
277
+ const { resetState } = useObservableContext();
278
+ useEffect(() => console.log( 'Reset component rendered.....' ));
279
+ return ( <button onClick={ resetState }>reset context</button> );
280
+ });
281
+ Reset.displayName = 'Reset';
282
+ export default Reset;
283
+
284
+
285
+ ## License
286
+
287
+ MIT
package/package.json CHANGED
@@ -78,5 +78,5 @@
78
78
  "test:watch": "eslint --fix && jest --updateSnapshot --watchAll"
79
79
  },
80
80
  "types": "dist/index.d.ts",
81
- "version": "2.1.1"
81
+ "version": "2.1.3"
82
82
  }