v6.0.35

use-focus-return

Capture last focused element on the page and return focus to it once condition is met
Import

Usage

use-focus-return automatically manages focus returning to last focused element when given condition is met. For example it is used in Modal component to restore focus after modal was closed.

Try closing modal with Escape key and see how focus returns to button after modal closes:

In most cases you would want to use this hook with use-focus-trap.

useFocusReturn({
// Is region with focus trap active?
// When it activates hook saves document.activeElement to internal state
// and focuses this element once focus trap is deactivated
opened: false,
// Determines whether focus should be returned automatically, true by default
shouldReturnFocus: true,
});

If shouldReturnFocus option is set to false you can call returned function to focus last active element:

const returnFocus = useFocusReturn({
opened: false,
shouldReturnFocus: false,
});
// ... later
returnFocus();

Definition

function useFocusReturn(options: { opened: boolean; shouldReturnFocus?: boolean }): () => void;