Skip to content

[DOCS] useOnClickOutside potential infinite rerender #693

@just2102

Description

@just2102

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:

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

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions