Rooks
HooksEvent Handling

useFocus

Provides focus and blur props for an element's own focus boundary.

About

useFocus returns React focus handlers for one element. Its callbacks run only when that element itself gains or loses focus; focus events bubbling from descendants are ignored.

Example

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

export default function FocusStatus() {
  const [focused, setFocused] = useState(false);
  const { focusProps } = useFocus<HTMLInputElement>({
    onFocusChange: setFocused,
  });

  return (
    <label>
      Project name
      <input {...focusProps} />
      <span>{focused ? "Editing" : "Not editing"}</span>
    </label>
  );
}

Parameters

Pass an object with any of these optional callbacks:

  • onFocus(event): runs when the immediate target receives focus.
  • onBlur(event): runs when the immediate target loses focus.
  • onFocusChange(isFocused): receives true after focus and false after blur.

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

Return value

The hook returns { focusProps }. Spread focusProps, which contains onFocus and onBlur, onto the intended element. The hook does not return focus state or imperative focus() and blur() methods.

Behavior and lifecycle

The handlers compare event.target with event.currentTarget to exclude descendant focus events. They are memoized against the supplied callbacks and create no native subscription or cleanup resource.

Compatibility and accessibility

This hook uses React focus events and is safe during server rendering. Attach the props to a naturally focusable control, or supply correct keyboard behavior and tabIndex when using a custom widget. Do not remove the visible focus indicator.

On this page