Skip to content

Commit c504248

Browse files
committed
Fix to use useRef instead of useState to avoid forcing a re-render
1 parent eb30f70 commit c504248

File tree

1 file changed

+16
-14
lines changed

1 file changed

+16
-14
lines changed

src/react/hooks/useSubscription.ts

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,12 @@ export function useSubscription<TData = any, TVariables = OperationVariables>(
3838
});
3939
});
4040

41-
const [canResetObservable, setCanResetObservable] = useState(false);
41+
const canResetObservableRef = useRef(false);
4242
useEffect(() => {
43-
return () => setCanResetObservable(true);
44-
}, [])
43+
return () => {
44+
canResetObservableRef.current = true;
45+
};
46+
}, []);
4547

4648
const ref = useRef({ client, subscription, options });
4749
useEffect(() => {
@@ -51,24 +53,24 @@ export function useSubscription<TData = any, TVariables = OperationVariables>(
5153
}
5254

5355
if (options?.skip) {
54-
if (!options?.skip !== !ref.current.options?.skip || canResetObservable) {
56+
if (!options?.skip !== !ref.current.options?.skip || canResetObservableRef.current) {
5557
setResult({
5658
loading: false,
5759
data: void 0,
5860
error: void 0,
5961
variables: options?.variables,
6062
});
6163
setObservable(null);
62-
setCanResetObservable(false);
64+
canResetObservableRef.current = false;
6365
}
6466
} else if (
65-
shouldResubscribe !== false && (
66-
client !== ref.current.client ||
67-
subscription !== ref.current.subscription ||
68-
options?.fetchPolicy !== ref.current.options?.fetchPolicy ||
69-
!options?.skip !== !ref.current.options?.skip ||
70-
!equal(options?.variables, ref.current.options?.variables)
71-
) || canResetObservable
67+
(shouldResubscribe !== false &&
68+
(client !== ref.current.client ||
69+
subscription !== ref.current.subscription ||
70+
options?.fetchPolicy !== ref.current.options?.fetchPolicy ||
71+
!options?.skip !== !ref.current.options?.skip ||
72+
!equal(options?.variables, ref.current.options?.variables))) ||
73+
canResetObservableRef.current
7274
) {
7375
setResult({
7476
loading: true,
@@ -82,11 +84,11 @@ export function useSubscription<TData = any, TVariables = OperationVariables>(
8284
fetchPolicy: options?.fetchPolicy,
8385
context: options?.context,
8486
}));
85-
setCanResetObservable(false);
87+
canResetObservableRef.current = false;
8688
}
8789

8890
Object.assign(ref.current, { client, subscription, options });
89-
}, [client, subscription, options, canResetObservable]);
91+
}, [client, subscription, options, canResetObservableRef.current]);
9092

9193
useEffect(() => {
9294
if (!observable) {

0 commit comments

Comments
 (0)