Rooks
HooksEvent Handling

useFocusWithin

Provides focus props that track entry to and exit from an element subtree.

About

useFocusWithin observes a focus boundary that includes the target element and all of its descendants. Moving focus between children does not count as leaving the boundary.

Example

import { useState } from "react";
import { useFocusWithin } from "rooks";

export default function AddressFields() {
  const [active, setActive] = useState(false);
  const { focusWithinProps } = useFocusWithin<HTMLFieldSetElement>({
    onFocusWithinChange: setActive,
  });

  return (
    <fieldset {...focusWithinProps}>
      <legend>Address {active ? "(active)" : ""}</legend>
      <label>
        City <input name="city" />
      </label>
      <label>
        Country <input name="country" />
      </label>
    </fieldset>
  );
}

Parameters

Pass an object with any of these optional callbacks:

  • onFocusWithin(event): runs once when focus enters the target subtree.
  • onBlurWithin(event): runs once when focus leaves the target subtree.
  • onFocusWithinChange(value): receives true on entry and false on exit.

These private option shapes are shown inline and are not importable package types.

Return value

The hook returns { focusWithinProps }. Spread those onFocus and onBlur props onto the boundary element.

Behavior and lifecycle

A ref stores whether focus is currently inside. On blur, the hook checks relatedTarget; if the boundary still contains that next target, it stays active. Callback changes update the memoized React handlers. The hook installs no native event listeners and needs no unmount cleanup.

Compatibility and accessibility

The hook is safe during server rendering. It does not make an element focusable or implement composite-widget keyboard behavior. Keep each descendant control correctly labeled and preserve visible focus styles.

  • useFocus responds only to focus on the immediate target.

On this page