Skip to content

Commit

Permalink
Fix useImmediateEffect teardown
Browse files Browse the repository at this point in the history
  • Loading branch information
kitten committed Jun 3, 2019
1 parent 7c97dd9 commit 8bf1dd5
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
11 changes: 6 additions & 5 deletions src/hooks/useImmediateEffect.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useRef, useEffect } from 'react';
import { useRef, useEffect, useCallback } from 'react';

enum EffectState {
BeforeMount = 0,
Expand All @@ -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();
}
};
5 changes: 4 additions & 1 deletion src/hooks/useQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,10 @@ export const useQuery = <T = any, V = object>(

// Calls executeQuery on initial render immediately, then
// treats it as a normal effect
useImmediateEffect(executeQuery);
useImmediateEffect(() => {
executeQuery();
return () => unsubscribe.current();
}, [executeQuery]);

return [state, executeQuery];
};

0 comments on commit 8bf1dd5

Please sign in to comment.