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

127
Visualizações
Can't perform a React state update on an unmounted component with EventListener

I have the following piece of code on which I am getting warning two warnings:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

unmountComponentAtNode(): The node you're attempting to unmount was rendered by another copy of React.

    import React, { useState, useEffect } from "react";
    import GravatarList from "./GravatarList";
    import Header from "./Header";
    import { calculateNumberOfImages } from "./utils";
    
    const App = () => {
      const handle = () => {
        setState({ images: calculateNumberOfImages() });
      }
    
    
      useEffect(() => {
          return () => {
    
            window.removeEventListener('resize', () => handle())
            window.removeEventListener('scroll', () => handle())
          }
       }, [])
    
    
      const [state, setState] = useState(() => {
        
        window.addEventListener("scroll", () => handle());
        window.addEventListener("resize", () => handle());
      
        return { images: calculateNumberOfImages() };
      });
    
      return (
        <div>
          
          <Header />
          <GravatarList state={state} />
        </div>
      );
    };
    
    export default App;

I can't seem to figure out what I am doing wrong as I have already cleared the listeners in useEffect.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The issue here is that the event callbacks you are trying to remove aren't the same callbacks you added to begin with. The issue is because you are using anonymous functions to call the function updating state.

You should also not use the state initializer function to do side effects like adding event listeners.

Move the handle callback and adding of event listeners into the mounting useEffect hook. Pass the handle callback reference to the add/remove functions,

const App = () => {
  const [state, setState] = useState(() => ({
    images: calculateNumberOfImages()
  }));

  useEffect(() => {
    const handle = () => {
      setState({ images: calculateNumberOfImages() });
    };

    window.addEventListener("scroll", handle);
    window.addEventListener("resize", handle);
  
    return () => {
      window.removeEventListener('resize', handle);
      window.removeEventListener('scroll', handle);
    }
   }, []);

  return (
    <div>
      <Header />
      <GravatarList state={state} />
    </div>
  );
};
over 4 years ago · Santiago Trujillo 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