title: Why is functional component nested function using a stale state value?
body: <p>My component fetches and displays posts using infinite scrolling (via an <code>IntersectionObserver</code>). The API call that the component makes is dependent on the current number of fetched posts. This is passed as an offset to the API call.</p>
  <p>The desired effect is that, if the <code>posts</code> array is empty, its length is 0 and my API will return the first 5 posts. When the last post in the UI intersects with the viewport, another fetch is made, but this time the API call is passed an offset of 5, so the API skips the first 5 posts in the collection and returns the next 5 instead.</p>
  <p>Here is my code:</p>
  <pre><code>export default function Feed() {
    const [posts, setPosts] = useState([]);
  
    const fetchPosts = async () =&gt; {
      const newPosts = await postAPI.getFeed(posts.length);
      setPosts((prevPosts) =&gt; [...prevPosts, ...newPosts]);
    };
  
    useEffect(fetchPosts, []);
  
    const observerRef = useRef(
      new IntersectionObserver(([entry]) =&gt; {
        if (entry.isIntersecting) {
          observerRef.current.unobserve(entry.target);
          fetchPosts();
        }
      })
    );
  
    const observePost = useCallback((node) =&gt; node &amp;&amp; observerRef.current.observe(node), []);
  
    return (
      &lt;&gt;
        {posts.map((post) =&gt; {
          const key = post._id;
          const isLastPost = key === posts.at(-1)._id;
          const callbackRef = !isLastPost ? undefined : observePost; //only if last post in state, watch it!
          
          return &lt;PostCard {...{ key, post, callbackRef }} /&gt;;
        })}
      &lt;/&gt;
    );
  }
  </code></pre>
  <p>However, every time the <code>fetchPosts</code> function is called, the value it uses for <code>posts.length</code> is 0 - the number the function was originally created with.</p>
  <p>Can someone explain to me why the closure over <code>posts.length</code> is stale here? I thought that every time a component re-renders, all nested functions within it were recreated from scratch? As such, surely the <code>fetchPosts</code> function should be using the latest value of <code>posts.length</code> every time it is called? Any help is appreciated! :)</p>