UnflowUI
ComponentsHooks

useDeferredFocus

Moves focus after a controlled value changes, once the element to focus exists in its new place. Used by ListEditor.

Overview

In a controlled list, the parent commits the next value, so the row you want to focus (a newly added input, or the row that just moved) only exists after the next render. useDeferredFocus remembers how to find that element and focuses it once the value it watches changes.

It is used by ListEditor to focus a new row after adding and to keep focus on a row after moving or removing one.

Import

import { useDeferredFocus } from '@unflowio/ui/hooks/useDeferredFocus';

Parameters

ParamTypeDescription
dependencyunknownThe value to wait for. Pending focus runs after it changes (compared by reference)

Return value

TypeDescription
(resolve: () => HTMLElement | null | undefined) => voidSchedules focus. resolve runs after the next change of dependency and should return the element to focus

Usage

Call the returned function, then the change handler:

import { useRef } from 'react';
import { useDeferredFocus } from '@unflowio/ui/hooks/useDeferredFocus';

function TagList({ value, onChange }: { value: string[]; onChange: (next: string[]) => void }) {
  const listRef = useRef<HTMLUListElement>(null);
  const focusAfterChange = useDeferredFocus(value);

  const add = () => {
    focusAfterChange(() => listRef.current?.querySelector<HTMLElement>('li:last-child input'));
    onChange([...value, '']);
  };

  return (
    <>
      <ul ref={listRef}>
        {value.map((tag, index) => (
          <li key={index}>
            <input
              aria-label={`Tag ${index + 1}`}
              value={tag}
              onChange={(event) =>
                onChange(value.map((t, i) => (i === index ? event.target.value : t)))
              }
            />
          </li>
        ))}
      </ul>
      <button onClick={add}>Add tag</button>
    </>
  );
}

Implementation notes

Only the latest request runs. Scheduling twice before the value changes keeps the second resolve.

Nothing happens if the value never changes. If the parent rejects the change and passes the same value back, the pending focus waits until the next real change. Schedule focus only right before calling onChange.

Resolve lazily. Query the DOM inside resolve, not before calling the scheduler: the element usually doesn't exist yet.

Accessibility

Moving focus to the element the user just created or moved keeps keyboard and screen reader users in place. Without it, focus falls back to body when the focused row re-renders or is removed.