[DOCS] useOnClickOutside potential infinite rerender

Author: just2102Created May 21, 2025Updated May 23, 2025
Labelsdocumentation

Describe the problem

Default eventListenerOptions = {} in useOnClickOutside causes unnecessary re-subscriptions on every render https://usehooks-ts.com/react-hook/use-on-click-outside

In useOnClickOutside, the default parameter for eventListenerOptions is an empty object ({}). Because JavaScript creates a new {} on each render, the useEffect in useEventListener sees its options dependency change every time and tears down/re-attaches the listener on every render.

Steps to Reproduce: _- Import and call useOnClickOutside(ref, handler) without passing eventListenerOptions.

  • Add a debug log inside the hook’s useEffect.
  • Trigger a re-render of your component (e.g. via state update).
  • Observe that the listener is removed and re-added on each render._

Expected Behavior: Listeners should only be (un)mounted when truly necessary. By defaulting eventListenerOptions to undefined (or making it optional), the dependency remains stable and avoids redundant re-subscriptions.

Suggested Fix: Change the signature to make eventListenerOptions optional, for example:

bash
export function useOnClickOutside<T>(
  ref: RefObject<T> | RefObject<T>[],
  handler: (event: Event) => void,
  eventType: EventType = 'mousedown',
  eventListenerOptions?: boolean | AddEventListenerOptions
): void { … }

Additional context

No response