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

125
Views
Make useEffect only run when component is in view (i.e. scrolled down to that component)

i have this code that updates a number from 2019 to 2022 but i want it to only run when the component is in view, meaning if they haven't scrolled to that part of the page the effect shouldn't run


useEffect(() => {
    setTimeout(() => {
        setTitle(2020)
    }, 2000)
    setTimeout(() => {
        setTitle(2021)
    }, 4000)
    setTimeout(() => {
        setTitle(2022)
    }, 6000)
},  []);

at the moment it updates the value even when you haven't scrolled down to that part of the page, is there a way to make useEffect only activate when scrolled to that section of the page or do you need to do it completely differently?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

window.addEventListener('scroll', function() {
    var element = document.querySelector('#main-container');
    var position = element.getBoundingClientRect();

    // checking whether fully visible
    if(position.top >= 0 && position.bottom <= window.innerHeight) {
        console.log('Element is fully visible in screen');
    }

    // checking for partial visibility
    if(position.top < window.innerHeight && position.bottom >= 0) {
        console.log('Element is partially visible in screen');
    }
});

Snippet from https://usefulangle.com/post/113/javascript-detecting-element-visible-during-scroll. Paste your code to the part where an element is fully in view. Remember to query select the element you want to have in view first.

about 4 years ago · Juan Pablo Isaza Report
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!