Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
import { useState, useEffect, useRef } from 'react';
// Usage
function App() {
// Ref for the element that we want to detect whether on screen
const ref = useRef();
// Call the hook passing in ref and root margin
// In this case it would only be considered onScreen if more ...
// ... than 300px of element is visible.
const onScreen = useOnScreen(ref, '-300px');
return (
<div style={{ height: '100vh' }}>
<h1>Scroll down to next section 👇</h1>
height: '100vh',
backgroundColor: onScreen ? '#23cebd' : '#efefef'
{onScreen ? (
<h1>Hey I'm on the screen</h1>
<img src="" />
) : (
<h1>Scroll down 300px from the top of this section 👇</h1>
// Hook
function useOnScreen(ref, rootMargin = '0px') {
// State and setter for storing whether element is visible
const [isIntersecting, setIntersecting] = useState(false);
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => {
// Update our state when observer callback fires
if (ref.current) {
return () => {
}, []); // Empty array ensures that effect is only run on mount and unmount
return isIntersecting;
Copy link

@ianobermiller Good call, updated!

Copy link

@mattfysh and @Andarist: Good points! So I'm thinking it would make sense to pass ref.current in input array so that effect is recalled if it changes and then wrap entire effect function body in if (ref.current) { ... } so that it does nothing if ref.current is falsy. Thoughts?

Copy link

I agree. I do believe ref.current should be passed as argument of useEffect line 58. Currently if the ref changes, nothing happens and the previous is leaked.

Copy link

You may also consider returning the ref from the hook instead of passing it as argument, c.f.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment