Skip to content

Focus Management React

DodaTech 4 min read

title: "Focus Management with useRef and useEffect" weight: 14 description: "Learn how to manage focus in React components using useRef to reference elements and useEffect to programmatically set focus when components mount, update, or respond to user interactions." date: 2026-06-28 lastmod: 2026-06-28 tags: [accessibility, react]


Focus management in React uses the useRef hook to create references to DOM elements and the useEffect hook to programmatically call focus when components mount (modals, panels), after state changes, or in response to user interactions.

## What You'll Learn

You will use useRef and useEffect to manage focus, implement focus trapping in modals, return focus to trigger elements, and handle focus in dynamic lists and navigation.

## Why It Matters

React's virtual DOM does not automatically manage focus. When content appears or disappears dynamically -- modals opening, navigation changing, lists updating -- focus must be managed manually to maintain an accessible experience.

## Real-World Use

A user opens a modal by clicking a button. Without focus management, focus stays on the button while the modal appears elsewhere. The screen reader user cannot find the modal content. With proper hooks, focus moves to the modal heading when it opens.

## Focus Management Flow

```mermaid
flowchart TD
  A[Event Triggered] --> B[State Update]
  B --> C[Re-render]
  C --> D[useEffect Runs]
  D --> E[current.focus]
  E --> F[Focus on Target]

Implementing Focus Management

Use useRef to target elements and useEffect to trigger focus.

import { useRef, useEffect } from 'react';

function Modal({ isOpen, onClose, children }) {
  const closeRef = useRef(null);
  const previousFocus = useRef(null);

  useEffect(() => {
    if (isOpen) {
      previousFocus.current = document.activeElement;
      closeRef.current.focus();
    } else if (previousFocus.current) {
      previousFocus.current.focus();
    }
  }, [isOpen]);

  useEffect(() => {
    function handleKeyDown(e) {
      if (e.key === 'Escape' && isOpen) {
        onClose();
      }
    }
    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  return (
    <div role="dialog" aria-modal="true" aria-label="Dialog">
      <div>
        {children}
        <button ref={closeRef} onClick={onClose}>
          Close
        </button>
      </div>
    </div>
  );
}
// Focus on newly added items in a list
function TodoList() {
  const [items, setItems] = useState([]);
  const lastItemRef = useRef(null);

  const addItem = () => {
    const newItem = { id: Date.now(), text: `Item ${items.length + 1}` };
    setItems([...items, newItem]);
  };

  useEffect(() => {
    if (lastItemRef.current) {
      lastItemRef.current.focus();
    }
  }, [items.length]);

  return (
    <div>
      <button onClick={addItem}>Add Item</button>
      <ul>
        {items.map((item, index) => (
          <li
            key={item.id}
            ref={index === items.length - 1 ? lastItemRef : null}
            tabIndex={-1}
          >
            {item.text}
          </li>
        ))}
      </ul>
    </div>
  );
}
// Focus trap utility
function FocusTrap({ children, active }) {
  const containerRef = useRef(null);

  useEffect(() => {
    if (!active) return;

    const container = containerRef.current;
    const focusable = container.querySelectorAll(
      'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
    );

    function handleTab(e) {
      if (e.key !== 'Tab') return;
      const first = focusable[0];
      const last = focusable[focusable.length - 1];

      if (e.shiftKey && document.activeElement === first) {
        e.preventDefault();
        last.focus();
      } else if (!e.shiftKey && document.activeElement === last) {
        e.preventDefault();
        first.focus();
      }
    }

    container.addEventListener('keydown', handleTab);
    focusable[0]?.focus();
    return () => container.removeEventListener('keydown', handleTab);
  }, [active]);

  return <div ref={containerRef}>{children}</div>;
}

Common Mistakes

  • Not moving focus into newly opened modals
  • Not returning focus when modals close
  • Using autoFocus attribute instead of useEffect
  • Forgetting to clean up event listeners in useEffect
  • Not handling the case when no element needs focus
  • Breaking focus when list items are reordered
  • Not making dynamically focused elements tabIndex={-1}

Practice and Challenge

Practice 1: Add focus management to a modal component. Practice 2: Implement focus return when a modal closes. Practice 3: Create a focus trap for a mobile menu. Practice 4: Focus a newly added item in a dynamic list. Practice 5: Manage focus when navigating between routes.

Challenge: Build a multi-step form wizard in React with focus management at each step. When the user advances to the next step, focus should move to the first input in the new step. When going back, focus should return to the previous step's last input. Trap focus within active step.

FAQ

Why not use autoFocus?

autoFocus only works on initial page load. useEffect with refs gives you control at any point in the component lifecycle.

Do I need to manage focus in every component?

Only components that dynamically appear, disappear, or update content -- modals, navigation, dynamic lists, error messages.

What if the focused element is unmounted?

Store a reference to the previously focused element before the modal opens and restore focus when it closes.

How do I trap focus in a modal?

Listen for Tab key events in the modal container and cycle focus between the first and last focusable elements.

Should I remove tabIndex after focus?

No. tabIndex=-1 allows programmatic focus without adding the element to the tab order.

How do I handle focus in lists?

Use refs on specific items and trigger focus in useEffect when the list changes.

Mini Project

Create a focus management utility library with hooks: useFocusOnMount, useFocusReturn, useFocusTrap, and useFocusList. Each hook should be reusable and include proper cleanup. Demonstrate all four hooks in a single page with a modal, menu, dynamic list, and navigation.

What's Next

Keyboard Events in React covers handling keyboard events in React components.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro