Skip to content

Commit

Permalink
react utils: Add useConditionalEffect custom hook
Browse files Browse the repository at this point in the history
To replace useEdgeTriggeredEffect, which implicitly required a
constant callback; see
  zulip#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.
  • Loading branch information
chrisbobbe committed Mar 21, 2022
1 parent 0c114b7 commit d25d3ac
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/reactUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,24 @@ export const useEdgeTriggeredEffect = (
// No dependencies list -- the effect itself decides whether to act.
});
};

/**
* Like `useEffect`, but the callback only runs when `value` is true.
*
* Callers should wrap the callback in `useCallback` with an appropriate
* array of dependencies.
*
* The callback will run once at the beginning of every period of `value`
* being true, and again throughout such a period whenever the value of the
* callback changes.
*
* As with `useEffect`, the cleanup function, if provided, will run once for
* every time the callback is called. If `value` goes from true to false,
* the cleanup function will be called at that time.
*/
// The claims about when `cb` runs assume that useEffect doesn't run its
// callback on non-initial renders where its dependencies are unchanged. The
// docs could be clearer about that:
// https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
export const useConditionalEffect = (cb: () => void | (() => void), value: boolean): void =>
useEffect(() => (value ? cb() : undefined), [value, cb]);

0 comments on commit d25d3ac

Please sign in to comment.