State Variables become null When UseEffect hook is used

I’m trying to make new requests whenever user reach the bottom with the following;

useEffect(() => {
    const scrolling_function = () => {
      if((window.innerHeight + window.scrollY) >= document.body.offsetHeight-10){
        window.removeEventListener('scroll',scrolling_function)
        getMoviesFromApi()
      }
    }
    window.addEventListener('scroll', scrolling_function);
}, [])

But the state objects that I defined, such as:

const[selectedGenres, setSelectedGenres] = useState(new Set())

All becomes undefined in the inside of my useEffect hook, and thus my getMoviesFromApi() method does not work properly.

My question is, is that expected behavior? If so, how could I overcome it?

The getmoviesfromapi method:

const getMoviesFromApi = async () => {
    setLoading(true)
    let init, end;
    if(initialYear>endYear) {
      init = endYear
      end = initialYear
    } else {
      init = initialYear
      end = endYear
    }
    let res =await fetchMovies(init, end)
    setLoading(false)
    setMovies(res.results)
  }

The fetchMovies method:

const fetchMovies = async (startYear, endYear) => {
    let res;

    res = [];
    let genreQuery = "";
    let serviceQuery = "";
    for (let it = selectedGenres.values(), val= null; val=it.next().value; ) {
      genreQuery += "&genre=" + val;
    }
    for (let it = selectedServices.values(), val= null; val=it.next().value; ) {
      serviceQuery += "&service=" + val;
    }

    let countryQuery = "?country="+country;
    let yearQuery = "&year_min="+ startYear +"&year_max=" + endYear;
    let typeQuery = "&type=" + (isMovie ? "movie" : "series");
    let url = api_url + countryQuery + serviceQuery + typeQuery +"&order_by=year" + yearQuery
          + genreQuery + "&page=1&desc=true&language=en&output_language=en"

    await fetch(url, {
      "method": "GET",
    }).then(response => {
          res= response.json()
        })
        .catch(err => {
          console.error(err);
        });
    return res;
  };

Answer

You should add the necessary state objects and functions to the dependencies, and call the functions with useCallBack. You can be sure that you’re making it right by installing eslint-plugin-react-hooks as a dev dependency. You’d also need a cleanUp function for your effect hook.

useEffect( () =>{
    const scrolling_function = async () => {
      if((window.innerHeight + window.scrollY) >= document.body.offsetHeight-10){
        await getMoviesFromApi(false);
      }
    }

    window.addEventListener('scroll', scrolling_function);
    return function cleanUp() { //don't forget to clean up
      window.removeEventListener('scroll',scrolling_function);
    }
  }, [getMoviesFromApi]); //add method as dependency!

//...

const getMoviesFromApi = useCallback () => { //useCallBack is needed here!
   ...
}