title: how to execute cleanup function in useEffect() only when component unmounts
body: <p>I want to clear filters only when the component unmounts. So I wrote cleanup function only in <code>useEffect()</code>. But as I checked it with <code>console.log()</code>, 1 was printed after the component mounted too. What's wrong in this way?</p>
  <pre><code>useEffect(() =&gt; {
    return () =&gt; {
      clearFilters();
      console.log(1);
    };
  }, []);
  </code></pre>
  <p>Stack Snippet:</p>
  <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="true">
  <div class="snippet-code snippet-currently-hidden">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const { useState, useEffect } = React;
  
  const Example = () =&gt; {
      useEffect(() =&gt; {
          return () =&gt; {
              // clearFilters();
              console.log(1);
          };
      }, []);
      return &lt;div&gt;x&lt;/div&gt;;
  };
  
  const App = () =&gt; {
      const [showExample, setShowExample] = useState(false);
      
      return &lt;div&gt;
          &lt;label&gt;
              &lt;input type="checkbox" checked={showExample} onChange={({currentTarget: {checked}}) =&gt; setShowExample(checked)} /&gt;
              Show &lt;code&gt;Example&lt;/code&gt; component
          &lt;/label&gt;
          &lt;div&gt;
              {showExample ? &lt;Example /&gt; : null}
          &lt;/div&gt;
      &lt;/div&gt;;
  };
  
  const root = ReactDOM.createRoot(document.getElementById("root"));
  root.render(&lt;App /&gt;);</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="root"&gt;&lt;/div&gt;
  
  &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"&gt;&lt;/script&gt;
  &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"&gt;&lt;/script&gt;</code></pre>
  </div>
  </div>
  </p>
  <p>Here's a more detailed code below</p>
  <pre class="lang-js prettyprint-override"><code>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 = () =&gt; {
    const {
      filters: { byAscendingPrice, byStock, byFastDelivery, rating },
      dispatch,
    } = useFilterContext();
  
    const clearFilters = () =&gt; dispatch({ type: 'CLEAR_FILTERS' });
    useEffect(() =&gt; {
      return () =&gt; clearFilters();
    }, []);
  
    return (
       // Some components
    );
  };
  
  export default Filter;
  </code></pre>