@mks2508/mks-ui
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 visible

Once Only

const { ref, isInView } = useIsInView({ once: true });
// Once visible, stays true even when scrolled away

With Root Margin

const { ref, isInView } = useIsInView({
  rootMargin: '-100px 0px',
});
// Triggers 100px before the element reaches the viewport edge

API Reference

Parameters

PropertyTypeDefaultDescription
thresholdnumber | number[]0Visibility ratio to trigger
oncebooleanfalseOnly trigger once
rootMarginstring'0px'Margin around the root
rootElement | nullnullScroll container (null = viewport)

Return Value

PropertyTypeDescription
refRefCallback<Element>Attach to the observed element
isInViewbooleanWhether the element is in the viewport