From 8bf1dd561d90e0f78d688a99f088e7cb5f7c0071 Mon Sep 17 00:00:00 2001 From: Phil Pluckthun Date: Mon, 3 Jun 2019 14:13:43 +0100 Subject: [PATCH] Fix useImmediateEffect teardown --- src/hooks/useImmediateEffect.ts | 11 ++++++----- src/hooks/useQuery.ts | 5 ++++- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/hooks/useImmediateEffect.ts b/src/hooks/useImmediateEffect.ts index d926be91cb..ba45e7b9b9 100644 --- a/src/hooks/useImmediateEffect.ts +++ b/src/hooks/useImmediateEffect.ts @@ -1,4 +1,4 @@ -import { useRef, useEffect } from 'react'; +import { useRef, useEffect, useCallback } from 'react'; enum EffectState { BeforeMount = 0, @@ -9,22 +9,23 @@ enum EffectState { type Effect = () => void | (() => void); /** This executes an effect immediately on initial render and then treats it as a normal effect */ -export const useImmediateEffect = (effect: Effect) => { +export const useImmediateEffect = (effect: Effect, changes?: any[]) => { const state = useRef(EffectState.BeforeMount); + const execute = useCallback(effect, changes); useEffect(() => { // Initially we skip executing the effect since we've already done so on // initial render, then we execute it as usual if (state.current === EffectState.Render) { - return effect(); + return execute(); } else { state.current = EffectState.Render; } - }, [effect]); + }, [execute]); // On initial render we just execute the effect if (state.current === EffectState.BeforeMount) { state.current = EffectState.AfterMount; - effect(); + execute(); } }; diff --git a/src/hooks/useQuery.ts b/src/hooks/useQuery.ts index 2cc890269f..a2628c6f1c 100644 --- a/src/hooks/useQuery.ts +++ b/src/hooks/useQuery.ts @@ -69,7 +69,10 @@ export const useQuery = ( // Calls executeQuery on initial render immediately, then // treats it as a normal effect - useImmediateEffect(executeQuery); + useImmediateEffect(() => { + executeQuery(); + return () => unsubscribe.current(); + }, [executeQuery]); return [state, executeQuery]; };