Hooks
useIsInView
Hook that detects when an element enters or exits the viewport using IntersectionObserver.
useIsInView
A hook that uses the IntersectionObserver API to detect when an element enters or exits the viewport.
Import
import { useIsInView } from '@mks2508/mks-ui/react';Basic Usage
function AnimatedSection() {
const { ref, isInView } = useIsInView();
return (
<div
ref={ref}
style={{
opacity: isInView ? 1 : 0,
transform: isInView ? 'translateY(0)' : 'translateY(20px)',
transition: 'all 0.6s ease-out',
}}
>
<h2>I animate in when visible</h2>
</div>
);
}With Threshold
const { ref, isInView } = useIsInView({ threshold: 0.5 });
// Triggers when 50% of the element is visibleOnce Only
const { ref, isInView } = useIsInView({ once: true });
// Once visible, stays true even when scrolled awayWith Root Margin
const { ref, isInView } = useIsInView({
rootMargin: '-100px 0px',
});
// Triggers 100px before the element reaches the viewport edgeAPI Reference
Parameters
| Property | Type | Default | Description |
|---|---|---|---|
threshold | number | number[] | 0 | Visibility ratio to trigger |
once | boolean | false | Only trigger once |
rootMargin | string | '0px' | Margin around the root |
root | Element | null | null | Scroll container (null = viewport) |
Return Value
| Property | Type | Description |
|---|---|---|
ref | RefCallback<Element> | Attach to the observed element |
isInView | boolean | Whether the element is in the viewport |