Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
React useRef scrollIntoView only fires once

I'm trying to scroll to an element when it comes into view. The problem is that it only works on a reload when it's already in view.

I've tried debugging it, but the ref seems to be correct and the conditionals pass. There is no return or error message so I don't know how to debug this further.

The hook works as it should so I'm really struggling to figure out what the cause is...

I need to put this in useEffect later on, but even this basic setup doesn't work. Any help is very much appreciated!

EDIT: I need to get this in the center of the screen so that I can overtake the scroll and animate the element on scroll. If I already start that functionality without it being centered, it'll stick to the bottom of the screen while it animates.

This is the component

const Component = () => {
    const sectionRef = useRef<HTMLDivElement>(null);
    const isOnScreen = useOnScreen(sectionRef);
    
    if (isOnScreen && sectionRef?.current) {
        sectionRef.current.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest'});
    }
    
    return ( 
        <section ref={sectionRef}>
            // ...child components
        </section>
    )
}

export default Component

This is the hook

import { useEffect, useState, useRef, RefObject } from 'react';

export default function useOnScreen(ref: RefObject<HTMLElement>) {
  const observerRef = useRef<IntersectionObserver | null>(null);
  const [isOnScreen, setIsOnScreen] = useState(false);

  useEffect(() => {
    observerRef.current = new IntersectionObserver(([entry]) =>
      setIsOnScreen(entry.isIntersecting)
    );
  }, []);

  useEffect(() => {
    if (ref.current) {
        observerRef.current?.observe(ref.current);
    }

    return () => {
      observerRef.current?.disconnect();
    };
  }, [ref]);

  return isOnScreen;
}
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!