Rehooks
Hooks

useFocus

A hook that returns a ref and a boolean indicating whether the element is currently focused.

useFocus

A hook that returns a ref and a boolean indicating whether the element is currently focused.

Usage

import { useFocus } from "rehooks-ts";
 
function Component() {
  const [ref, isFocused] = useFocus<HTMLInputElement>((focusState) => {
    console.log("Focus state:", focusState);
  });
 
  return (
    <div>
      <input ref={ref} type="text" placeholder="Focus me!" />
      <p>The input is currently {isFocused ? "focused" : "unfocused"}</p>
    </div>
  );
}

API

useFocus

function useFocus<T extends HTMLElement>(
  callback?: UseFocusCallback,
): [RefObject<T>, boolean];

Returns a ref and boolean indicating whether the element is currently focused.

Parameters

NameTypeDescription
callback?UseFocusCallbackOptional callback to run in focus and blur HTML element mode. The callback is called with a boolean indicating whether the element is currently focused.
THTMLElementThe type of the HTML element to focus.

Returns

NameTypeDescription
refRefObject<T>A ref object that can be used to access the HTML element.
isFocusedbooleanA boolean indicating whether the element is currently focused.

On this page