Skip to main content

useVisibilityChange

A custom hook that registers callback functions to be called when the document's visibility state changes.

When document.visibilityState becomes visible (visible), the onShow callback is called. When it becomes hidden (hidden), the onHide callback is called.


Code

🔗 View source code


Interface

typescript
type VisibilityChangeCallbackAction = (
event: Event,
visibilityState: DocumentVisibilityState
) => void;

interface useVisibilityChangeProps {
onShow?: VisibilityChangeCallbackAction;
onHide?: VisibilityChangeCallbackAction;
enabled?: boolean; // default: true
}
typescript
function useVisibilityChange({
onShow,
onHide,
enabled = true,
}: UseVisibilityChangeProps = {}): void;

Options

NameTypeDefaultDescription
onShowVisibilityChangeCallbackAction-Callback called when the document becomes visible (visible)
onHideVisibilityChangeCallbackAction-Callback called when the document becomes hidden (hidden)
enabledbooleantrueWhether visibility change detection is enabled

Usage

typescript
import { useVisibilityChange } from '@modern-kit/react';

const Example = () => {
useVisibilityChange({
onShow: (event: Event, visibilityState: DocumentVisibilityState) => { /* ... */},
onHide: (event: Event, visibilityState: DocumentVisibilityState) => { /* ... */}
});

return (
<div>{/* ... */}</div>
)
};

Example

Try switching to another tab and coming back!