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

80
Views
Intersection Observer fails to update state

I am trying to create infinite scrolling with intersection observer, but callback function fails to update state. When i scroll down i can see states's console.log output but its always same.

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

// Css
import './index.css';

// Components
import QuadColors from './colors-components/quad-colors';
import SearchBar from '../../components/searchBar';
export default function colors() {
  const [renderColorSets, setRenderColorSets] = useState(5);
  const containerRef = useRef();
  const footRef = useRef();

  // Intersection Observer
  useEffect(() => {
    const observer = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting) {
        setRenderColorSets(renderColorSets + 1);
        console.log(renderColorSets);
      }
    });

    observer.observe(footRef.current);
  }, []);

  return (
    <>
      <SearchBar placeholder="Color" />
      <div className="random-colors-container" ref={containerRef}>
        {[...Array(renderColorSets)].map(() => {
          return <QuadColors />;
        })}
        <div ref={footRef} />
      </div>
    </>
  );
}```
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You should give an update function to setState, not an updated value itself (cause of enclosured value within observer callback function). Try to do next:

if (entries[0].isIntersecting) {
  setRenderColorSets((prevColorSets) => prevColorSets + 1);
  console.log(renderColorSets);
}

Thus whenever you fire setState function - you have the latest value of state.

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!