Nisha Patel
Problem
I have a question about useEffect and useCallback.
I have react code that will request and load data when you scroll to the bottom of the screen.
My question is:
As you see at the bottom of the code, the final useEffect() is using the fetchData callback as a dependency. If I remove the dependency, the code works fine however the index state does not get updated.
Can anyone shed light of this curious occurrence?
What I know I know the useEffect dependencies are used to decided when the effect is run (if state of dependency changes). However I'm not yet sure how a callBack can change states. This hole in my knowledge may be where the answer to the strange reaction is.
Solution
When you remove fetchData as an external dependency from the last useEffect hook, you are closing over the "instance" of fetchData from the initial render cycle where index had a value of 2.
Without the fetchData dependency, then handleScroll gets a "copy" of that initial fetchData function then handleScroll is passed as a scroll event listener. The index value closed over in fetchData is used in the URL of the Axios GET request and it never sees any updated value.
By including the re-memoized fetchData (from the useCallback hook) in the dependency array, the useEffect hook properly cleans up the previous handleScroll "instance" that was used as a scroll event handler and the new "instance" of handleScroll gets the new "instance" of fetchData which has the updated index state value closed over in callback scope.
Suggested blogs:
>How to conditionally render different arrays in React?
>Fix react useState and array.map not work issue
>Making infinite scrolling using react-query
>How does React State with JSON arrays affect performance?
>setlist{nosep} not work in the acronym package
>Fix ScrollIntoView not working issue
>Testing react component with jest
>How you can Show or hide elements in React?
>Testing react components using Hooks and Mocks
>Tips for using React Redux Hooks to show or hide React components