EventIntermediateBrowser APIshooks/events/useBlur.ts

useBlur

Run work when an element blurs.

Import

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

API

Signature

useBlur(ref, onBlur?) → boolean

When to use

Use useBlur 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 · useBlur
Editor
function Email() {
  const ref = useRef<HTMLInputElement>(null);
  const blurred = useBlur(ref, () => console.log('validate'));
  return <input ref={ref} data-blurred={blurred} />;
}
Preview

Implementation source

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

hooks/events/useBlur.ts
import { useEffect, useState, type RefObject } from 'react';
import { isBrowser } from '../utility/isBrowser';
import { useLatest } from '../utility/useLatest';

/**
 * Invokes a callback when the element blurs.
 * Returns whether the element is currently blurred (not focused).
 */
export function useBlur<T extends HTMLElement>(
  ref: RefObject<T | null>,
  onBlur?: (event: FocusEvent) => void,
): boolean {
  const [blurred, setBlurred] = useState(true);
  const onBlurRef = useLatest(onBlur);

  useEffect(() => {
    if (!isBrowser()) return;
    const el = ref.current;
    if (!el) return;

    const handleFocus = () => setBlurred(false);
    const handleBlur = (event: FocusEvent) => {
      setBlurred(true);
      onBlurRef.current?.(event);
    };

    el.addEventListener('focus', handleFocus);
    el.addEventListener('blur', handleBlur);
    return () => {
      el.removeEventListener('focus', handleFocus);
      el.removeEventListener('blur', handleBlur);
    };
  }, [ref, onBlurRef]);

  return blurred;
}

Copy-paste example

useBlur.example.tsx
'use client';

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

export function Email() {
  const ref = useRef<HTMLInputElement>(null);
  const blurred = useBlur(ref, () => console.log('validate'));
  return <input ref={ref} data-blurred={blurred} />;
}

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/useBlur.ts for implementation details