Go Back

2 min read

Detecting Element Visibility with React's `useOnScreen` Hook

profile

Nitin k

|

December 09, 2024

views

Have you ever wondered how websites trigger animations when you scroll? This is often achieved with Intersection Observer API. Let's explore a custom React hook called useOnScreen that makes detecting element visibility simple.

Why Use useOnScreen?

useOnScreen helps check if an element is visible within the viewport. This is useful for triggering animations, lazy-loading images, or tracking user engagement.

How It Works

Here's the core of the hook:

useOnScreen.ts

Key Features:

  • ref: Tracks the target element.
  • threshold: Defines how much of the element should be visible to trigger the callback.
  • rootMargin: Sets margins around the viewport.
  • once: Stops observing after the first intersection.

Example Use Case

index.tsx

Conclusion

With useOnScreen, detecting element visibility becomes straightforward. It leverages the Intersection Observer API to provide an elegant solution for scroll-based animations, lazy-loading, and more. Try it in your next project!