Skip to content

Commit 69a616b

Browse files
committed
react utils: Add useConditionalEffect custom hook
To replace useEdgeTriggeredEffect, which implicitly required a constant callback; see #5300 (comment) and this bit of useEdgeTriggeredEffect's jsdoc: > The callback is not permitted to return a cleanup function, > because it's not clear what the semantics should be of when such a > cleanup function would be run.
1 parent 61dcfa8 commit 69a616b

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

src/reactUtils.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,3 +115,24 @@ export const useEdgeTriggeredEffect = (
115115
// No dependencies list -- the effect itself decides whether to act.
116116
});
117117
};
118+
119+
/**
120+
* Like `useEffect`, but the callback only runs when `value` is true.
121+
*
122+
* Callers should wrap the callback in `useCallback` with an appropriate
123+
* array of dependencies.
124+
*
125+
* The callback will run once at the beginning of every period of `value`
126+
* being true, and again throughout such a period whenever the value of the
127+
* callback changes.
128+
*
129+
* As with `useEffect`, the cleanup function, if provided, will run once for
130+
* every time the callback is called. If `value` goes from true to false,
131+
* the cleanup function will be called at that time.
132+
*/
133+
// The claims about when `cb` runs assume that useEffect doesn't run its
134+
// callback on non-initial renders where its dependencies are unchanged. The
135+
// docs could be clearer about that:
136+
// https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
137+
export const useConditionalEffect = (cb: () => void | (() => void), value: boolean): void =>
138+
useEffect(() => (value ? cb() : undefined), [value, cb]);

0 commit comments

Comments
 (0)