EventIntermediateBrowser APIshooks/events/useFocus.ts

useFocus

Track focus on an element.

Import

TypeScript
import { useFocus } from '@/hooks';

API

Signature

useFocus(ref) → boolean

When to use

Use useFocus instead of re-implementing the same pattern in multiple components.

SSR / Next.js

No-ops until document/window exist.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useFocus
Editor
function Field() {
  const ref = useRef<HTMLInputElement>(null);
  const focused = useFocus(ref);
  return <input ref={ref} style={{ outlineColor: focused ? 'teal' : undefined }} />;
}
Preview

Implementation source

Full library source for useFocus — copy into your project when you are not installing a package yet.

hooks/events/useFocus.ts
import { useState, type RefObject } from 'react';
import { useEventListener } from './useEventListener';

/** Tracks focus state for an element. */
export function useFocus<T extends HTMLElement>(
  ref: RefObject<T | null>,
  options: { enabled?: boolean } = {},
): boolean {
  const [focused, setFocused] = useState(false);
  const { enabled = true } = options;
  useEventListener('focus', () => setFocused(true), ref, { enabled });
  useEventListener('blur', () => setFocused(false), ref, { enabled });
  return focused;
}

Copy-paste example

useFocus.example.tsx
'use client';

import { useRef } from 'react';
import { useFocus } from '@/hooks';

export function Field() {
  const ref = useRef<HTMLInputElement>(null);
  const focused = useFocus(ref);
  return <input ref={ref} style={{ outlineColor: focused ? 'teal' : undefined }} />;
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Pass all relevant refs to useClickOutside (trigger + panel). Prefer useLatest for handlers.
  • Source of truth: open hooks/events/useFocus.ts for implementation details