useSmartVideo

An advanced video hook that combines intersection logic with playback control for automated "smart" behavior.

Important

For autoPlay to work reliably across all browsers, the video element MUST have the muted and playsInline attributes set. Most browsers will block unmuted autoplay.

Tip

This hook depends on useIntersectionObserver. Ensure that the parent container doesn't have overflow: hidden in a way that prevents the observer from detecting visibility correctly.

Note

The threshold value determines how much of the video must be visible before autoPlay triggers. A value of 0.5 means 50% of the video must be in the viewport.

Installation

bash

Description

The useSmartVideo leverages the useIntersectionObserver to trigger video actions based on the element's visibility in the viewport. It is ideal for social media feeds or landing pages where videos should play automatically when visible and pause or reset when scrolled out of view. It includes safety checks for browser autoplay policies (requiring muted and playsInline) and manages the internal playback state reactively.

Parameters

NameTypeDescription
options.autoPlaybooleanIf true, the video plays automatically when it becomes visible. Default: 'false'.
options.pauseOnExitbooleanIf true, the video pauses when it leaves the viewport. Default: 'false'.
options.resetOnExitbooleanIf true, resets the video to the beginning when it leaves the viewport. Default: 'false'.
options.thresholdnumberVisibility ratio (0.0 to 1.0) required to trigger 'visible' state. Default: 0.5.

Return values

NameTypeDescription
videoRefReact.RefObject<HTMLVideoElement | null>The ref to be assigned to the <video> element.
isPlayingbooleanReactive state indicating if the video is currently playing.
isVisiblebooleanReactive state indicating if the video is currently within the viewport threshold.
play() => Promise<void>Imperative function to start video playback.
pause() => voidImperative function to pause video playback.
stop() => voidPauses the video and resets currentTime to 0.
reset() => voidResets currentTime to 0 without changing the playback state.

Demo

Smart Video

Status: PausedVisibility: Not visible

Source code

tsx