useOnEscapePress execution order with nested components
When multiple useOnEscapePress hooks are active simultaneously, the callbacks execute in reverse order. If a parent component and a child component both call useOnEscapePress, the child component's callback executes first, followed by the parent's callback. Each callback can call preventDefault() on the event to prevent further callbacks from executing.
useOnEscapePress dependency list parameter
useOnEscapePress takes a React.DependencyList as its second argument to memoize the callback, similar to useCallback. If this argument is omitted, the hook assumes the callback is already memoized. Failing to provide the correct dependency list can result in degraded performance.
useOnEscapePress hook basic behavior
useOnEscapePress is a utility Hook that calls a user-provided function when the Escape key is pressed. The hook sets up a keydown event listener on window.document and executes the user-provided function if the Escape key was pressed and the preventDefault method has not yet been called on the event object.
useOnEscapePress API parameters
useOnEscapePress takes two parameters: onEscape (required, type: (event: KeyboardEvent) => void, the function to call when user presses the Escape key) and callbackDependencies (optional, type: React.DependencyList, array of dependencies for memoizing the given callback).
useOnEscapePress usage example
```javascript
const OverlayDemo = ({onEscape, children}) => {
useOnEscapePress(onEscape)
return <Box height="200px">{children}</Box>
}
function DemoComponent() {
const [isOpen, setIsOpen] = React.useState(false)
const toggleOverlay = React.useCallback(() => {
setIsOpen(isOpen => !isOpen)
}, [])
const closeOverlay = React.useCallback(() => {
setIsOpen(false)
}, [])
return (
<>
<Button onClick={toggleOverlay}>toggle</Button>
{isOpen && (
<OverlayDemo onEscape={closeOverlay}>
<Button>Button One</Button>
<Button>Button Two</Button>
</OverlayDemo>
)}
</>
)
}
render(<DemoComponent />)
```
This example shows how to use useOnEscapePress to close an overlay when the Escape key is pressed. The closeOverlay callback is memoized with useCallback, so no dependency list is passed to useOnEscapePress.
useOpenAndCloseFocus usage example
The following code shows how to use useOpenAndCloseFocus in a component:
```javascript
const Overlay = ({returnFocusRef, initialFocusRef, preventFocusOnOpen, children}) => {
const containerRef = React.useRef(null)
useOpenAndCloseFocus({containerRef, returnFocusRef, initialFocusRef, preventFocusOnOpen})
return (
<Box height="200px" ref={containerRef}>
{children}
</Box>
)
}
function Component() {
const returnFocusRef = React.useRef(null)
const initialFocusRef = React.useRef(null)
const [isOpen, setIsOpen] = React.useState(false)
return (
<Box sx={{'*': {':focus': {backgroundColor: 'red.5'}}}}>
<Button ref={returnFocusRef} onClick={() => setIsOpen(!isOpen)}>
toggle
</Button>
{isOpen && (
<Overlay returnFocusRef={returnFocusRef} initialFocusRef={initialFocusRef} preventFocusOnOpen={true}>
<Button>Button One</Button>
<Button ref={initialFocusRef}>Button Two</Button>
</Overlay>
)}
</Box>
)
}
render(<Component />)
```
This example demonstrates using useOpenAndCloseFocus to manage focus when an overlay component mounts and unmounts.
useOpenAndCloseFocus hook purpose and behavior
useOpenAndCloseFocus is a utility Hook that manages focusing an element when a component is first mounted and returns focus to another element on the page when that component unmounts. If no ref is passed to initialFocusRef, the hook focuses the first focusable element inside the container.
useOpenAndCloseFocus preventFocusOnOpen behavior
When the preventFocusOnOpen prop is passed and set to true, no focus will be applied when the component mounts, even if initialFocusRef prop is included. Only initial focus is prevented; focus will still be returned to returnFocusRef when the component unmounts.
useOpenAndCloseFocus parameters
The useOpenAndCloseFocus hook accepts the following parameters:
| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| initialFocusRef | React.RefObject<HTMLElement> | No | | Optional. The element to focus when the container is mounted on the page. |
| returnFocusRef | React.RefObject<HTMLElement> | Yes | | Required. The element to focus when the container is unmounted. |
| containerRef | React.RefObject<HTMLElement> | Yes | | Required. A ref for the containing element. |
| preventFocusOnOpen | React.RefObject<HTMLElement> | No | | Optional. When true, prevents focus when container is mounted. |
useSafeTimeout usage example
const {safeSetTimeout, safeClearTimeout} = useSafeTimeout()
let timeoutId = null
const handleOnClick = () => {
timeoutId = safeSetTimeout(() => window.alert('hello!'), 5000)
}
const cancelTimeout = () => {
safeClearTimeout(timeoutId)
}
return (
<>
<Button onClick={handleOnClick}>Click me</Button>
<Button onClick={cancelTimeout}>Cancel timeout</Button>
</>
)
useSafeTimeout Hook purpose and behavior
useSafeTimeout is a utility Hook that allows safely calling setTimeout and clearTimeout within a component. It ensures that all timeouts are cleared when the component unmounts, preventing memory leaks and errors from callbacks firing after unmount.
useSafeTimeout Hook API
useSafeTimeout returns an object with two methods: safeSetTimeout and safeClearTimeout. safeSetTimeout works like the native setTimeout, accepting a callback function and a delay in milliseconds, and returns a timeout ID. safeClearTimeout works like the native clearTimeout, accepting a timeout ID to cancel a pending timeout.