title: Can't access state inside function in React Function Component
body: <p>I have the following component in React:</p>
  
  <pre><code>import React, { useState, useEffect } from 'react';
  import api from '../../services/api';
  
  const Store = () =&gt; {
    const [products, setProducts] = useState([]);
    let pagination = null;
  
    const getProducts = async (page = 1) =&gt; {
      const { data } = await api.get('products', { params: { page } });
  
      setProducts([...products, ...data.products]);
      pagination = data.pagination;
  
      if (pagination.current &lt; pagination.max) {
        document.addEventListener('scroll', loadMore);
      }
    };
  
    const loadMore = () =&gt; {
      const { scrollTop, clientHeight, scrollHeight } = document.documentElement;
  
      if (scrollTop + clientHeight &gt;= scrollHeight - 300) {
        getProducts(pagination.current + 1);
        document.removeEventListener('scroll', loadMore);
      }
    };
  
    useEffect(() =&gt; {
      getProducts();
    }, []);
  
    useEffect(() =&gt; {
      console.log(products);
    }, [products]);
  
    return (
      &lt;div&gt;
        {products.map(product =&gt; (
          &lt;p&gt;{product.name}&lt;/p&gt;
        ))}
      &lt;/div&gt;
    );
  };
  
  export default Store;
  </code></pre>
  
  <p>My <code>console.log</code> inside the <code>useEffect</code> hook do print the products array correctly, and the component is also rendering the products titles correctly.</p>
  
  <p>But when I try to access the <code>products</code> variable inside the <code>getProducts</code> function it doesn't get the updated products value, it gets the value I have set in the <code>useState</code> hook.</p>
  
  <p><em>For example, if I start the state with one product, calling <code>products</code> within the <code>getProducts</code> function will always bring this one product, and not the ones loaded from the API fetch, that were correctly logged in the console.</em></p>
  
  <p>So, when I try to add more products to the end of the array it actually just add the products to an empty array.</p>
  
  <p>Any idea why this is happening? Being able to access the products state inside the <code>useState</code> hook but not inside the <code>getProducts</code> function?</p>