From 0aede51a70fd38ff6554a3964e4fb01bb0844646 Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Tue, 6 Apr 2021 13:16:29 +0300 Subject: [PATCH] fix: fast refresh issue with hooks Closes #5870 --- src/react/hooks/utils/useBaseQuery.ts | 33 ++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/src/react/hooks/utils/useBaseQuery.ts b/src/react/hooks/utils/useBaseQuery.ts index 7052df65fc0..cc168b4da7a 100644 --- a/src/react/hooks/utils/useBaseQuery.ts +++ b/src/react/hooks/utils/useBaseQuery.ts @@ -70,8 +70,39 @@ export function useBaseQuery( ? (result as QueryTuple)[1] : (result as QueryResult); + let _maybeFastRefresh: React.MutableRefObject; + + // @ts-expect-error: __DEV__ is a global exposed by react + if (__DEV__) { + /* eslint-disable react-hooks/rules-of-hooks */ + _maybeFastRefresh = useRef(false); + useEffect(() => { + return () => { + // Detect fast refresh, only runs multiple times in fast refresh + _maybeFastRefresh.current = true; + }; + }, []); // eslint-disable-line react-hooks/exhaustive-deps + /* eslint-enable react-hooks/rules-of-hooks */ + } + useEffect(() => { - return () => queryData.cleanup(); + if (_maybeFastRefresh && _maybeFastRefresh.current) { + /** + * This block only runs during fast refresh, the current resource and + * it's cache is disposed in the previous cleanup. Stop retaining and + * force a re-render to restart the hook. + */ + _maybeFastRefresh.current = false; + forceUpdate(); + return; + } + + return () => { + queryData.cleanup(); + // this effect can run multiple times during a fast-refresh + // so make sure we clean up the ref + queryDataRef.current = undefined; + } }, []); useEffect(() => queryData.afterExecute({ lazy }), [