Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

424
Visualizações
react-intersection-observer only works with the last elements

I'm trying to build the Lazy Loading feature with react-intersection-observer, the goal is to only load the images in the boxes if they're in the viewport.

  • Currently, when I scroll to the last elements - it will render out all of the images of the boxes.
  • But when I scroll up and the last boxes are out of the viewport, everything on top will disappear.
  • If I print out inView, this turns to true when scrolling to the last elements and turns false when the last elements are out of the viewport.

How to fix this problem so it will only render out the boxes that are in the viewport?


Demo gif:

enter image description here


My code:

App.js

export const AppContext = createContext();

function App() {
  const { ref, inView, entry } = useInView({
    rootMargin: "50px 0px",
    initialInView: true
    // triggerOnce: true,
  });

  return (
    <AppContext.Provider value={{ ref, inView, entry }}>
      <div className="App">
        <Posts />
      </div>
    </AppContext.Provider>
  );
}

export default App;

Post.js

import { useContext } from 'react'
import { AppContext } from '../App'

function Post({ post }) {
  const { ref, inView } = useContext(AppContext)
  return (
    <div className="post" ref={ref}>
      {inView ? 
        <img src={post.imgUrl} alt={post.title} className="post__img" loading="lazy" />
        : <div className="post__img" />
      }
      <h1 className="post__title">{post.title}</h1>
    </div>
  )
}

export default Post

Update:

I updated the Codesandbox link below to move useInView to Post.js and removed the Context API. It works now!

Edit Lazy Loading with react-intersection-observer

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Firstly you are using context, it maintains a single state but in your case you want to track all post items separately so,

Just bring the useInView hook inside each component of Post.js and remove it from App.js

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda