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

218
Visualizações
how to execute cleanup function in useEffect() only when component unmounts

I want to clear filters only when the component unmounts. So I wrote cleanup function only in useEffect(). But as I checked it with console.log(), 1 was printed after the component mounted too. What's wrong in this way?

useEffect(() => {
  return () => {
    clearFilters();
    console.log(1);
  };
}, []);

Stack Snippet:

const { useState, useEffect } = React;

const Example = () => {
    useEffect(() => {
        return () => {
            // clearFilters();
            console.log(1);
        };
    }, []);
    return <div>x</div>;
};

const App = () => {
    const [showExample, setShowExample] = useState(false);
    
    return <div>
        <label>
            <input type="checkbox" checked={showExample} onChange={({currentTarget: {checked}}) => setShowExample(checked)} />
            Show <code>Example</code> component
        </label>
        <div>
            {showExample ? <Example /> : null}
        </div>
    </div>;
};

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

Here's a more detailed code below

import React, { useEffect } from 'react';
import { useFilterContext } from 'contexts/FilterContext';
import classNames from 'classnames/bind';
import Rating from 'components/Rating/Rating';
import { Button, Form } from 'react-bootstrap';
import styles from './Filter.module.scss';

const cn = classNames.bind(styles);

const Filter = () => {
  const {
    filters: { byAscendingPrice, byStock, byFastDelivery, rating },
    dispatch,
  } = useFilterContext();

  const clearFilters = () => dispatch({ type: 'CLEAR_FILTERS' });
  useEffect(() => {
    return () => clearFilters();
  }, []);

  return (
     // Some components
  );
};

export default Filter;
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You might be using React's strict mode which simulates unmounting and remounting a component when a component is mounted. This causes double renders in development.

about 4 years ago · Juan Pablo Isaza Relatório

0

This is because of the strict mode. In Strict mode, react may invoke render phase lifecycles multiple times. So it prints 1 on the mounting of the component. But the interesting thing to note here is that it only happens in Development mode, not in Production mode.

Here's the link to read more about React's strict mode: Link

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