Description

Trigger focusing on an element whenever the user takes an action.
?

Reach for when

You want to programmatically toggle the focus on an input.

Code

function useFocus() {
  const ref = useRef(null);
  const setFocus = () => ref.current?.focus();
  return [ref, setFocus];
}

// Usage:
function SearchBar() {
  const [inputRef, focusInput] = useFocus();
  return (
    <>
      <input ref={inputRef} />
      <button onClick={focusInput}>Focus search</button>
    </>
  );
}