score:10

Accepted answer

Instead of returning ref.current from usePrevious return, ref since ref.current will be mutated at its reference and you will be able to receive the updated value within useEffect otherwise it will receive the value from its closure

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref;
}

Code:

const fromPrevStoriesIds = usePrevious(prevStoriesIds);

useEffect(() => {
    const fetchData = () => {
      axios
        .get("https://hacker-news.firebaseio.com/v0/newstories.json")
        .then(storyIds => {
          //   console.log("STORY IDs FETCHED ", storyIds.data.slice(0, 2));

          setPrevStoriesIds(storyIds.data.slice(0, 2));
          getAllNewStory(storyIds);
        });
    };
    fetchData();

    const doPolling = () => {
      var timer = setInterval(() => {
        axios
          .get("https://hacker-news.firebaseio.com/v0/newstories.json")
          .then(storyIds => {            
            console.log(
              "fromPrevStoriesIds INSIDE doPolling() ",
              fromPrevStoriesIds.current
            );

            if (
              fromPrevStoriesIds.current !== undefined &&
              !isEqual(fromPrevStoriesIds.current.sort(), storyIds.data.slice(0, 2).sort())
            ) {
              setPrevStoriesIds(storyIds.data.slice(0, 2));
              setNoOfNewStoryAfterPolling(
                differenceWith(
                  prevStoriesIds.sort(),
                  storyIds.data.slice(0, 2).sort(),
                  isEqual
                ).length
              );
              getAllNewStory(storyIds);
              setOpenNewItemAddedConfirmSnackbar(true);              
            }
          });
      }, 5000);
    };

    doPolling();

    // return () => {
    //   console.log("cleaning up");
    //   clearInterval(timer);
    // };
  }, [rowsPerPage, noOfNewStoryAfterPolling]);

Related Query

More Query from same tag