@samitouri / QOS-React / commits / 2738e84805

Removed an unnecessary wrapper object from state (#12383)

* Removed an unnecessary wrapper object from state * Moved unsubscribe from state to class field and tweaked comments

Brian Vaughn committed Mar 15, 2018 at 11:43 UTC 2738e84805820fbf4f7db1a521e22d44272455ab
1 file changed +9 -18
packages/create-subscription/src/createSubscription.js
+9 -18
@@ -51,9 +51,6 @@ export function createSubscription<Property, Value>(
51 };
52 type State = {
53 source: Property,
54 - unsubscribeContainer: {
55 - unsubscribe: Unsubscribe | null,
56 - },
54 value: Value | void,
55 };
56
@@ -61,22 +58,18 @@ export function createSubscription<Property, Value>(
58 class Subscription extends React.Component<Props, State> {
59 state: State = {
60 source: this.props.source,
64 - unsubscribeContainer: {
65 - unsubscribe: null,
66 - },
61 value:
62 this.props.source != null
63 ? getCurrentValue(this.props.source)
64 : undefined,
65 };
66
67 + _unsubscribe: Unsubscribe | null = null;
68 +
69 static getDerivedStateFromProps(nextProps, prevState) {
70 if (nextProps.source !== prevState.source) {
71 return {
72 source: nextProps.source,
77 - unsubscribeContainer: {
78 - unsubscribe: null,
79 - },
73 value:
74 nextProps.source != null
75 ? getCurrentValue(nextProps.source)
@@ -125,18 +118,16 @@ export function createSubscription<Property, Value>(
118 });
119 };
120
128 - // Store subscription for later (in case it's needed to unsubscribe).
129 - // This is safe to do via mutation since:
130 - // 1) It does not impact render.
131 - // 2) This method will only be called during the "commit" phase.
121 + // Store the unsubscribe method for later (in case the subscribable prop changes).
122 const unsubscribe = subscribe(source, callback);
133 -
123 invariant(
124 typeof unsubscribe === 'function',
125 'A subscription must return an unsubscribe function.',
126 );
127
139 - this.state.unsubscribeContainer.unsubscribe = unsubscribe;
128 + // It's safe to store unsubscribe on the instance because
129 + // We only read or write that property during the "commit" phase.
130 + this._unsubscribe = unsubscribe;
131
132 // External values could change between render and mount,
133 // In some cases it may be important to handle this case.
@@ -148,10 +139,10 @@ export function createSubscription<Property, Value>(
139 }
140
141 unsubscribe(state: State) {
151 - const {unsubscribe} = state.unsubscribeContainer;
152 - if (typeof unsubscribe === 'function') {
153 - unsubscribe();
142 + if (typeof this._unsubscribe === 'function') {
143 + this._unsubscribe();
144 }
145 + this._unsubscribe = null;
146 }
147 }
148