0

I'm stuck with an issue regarding React app. I have a CustomMap component that handles the mapbox Map instance. The key parts of the code, at least from my perspective are as follows:

const CustomMap = (props) => {
   const location = useSelector((state) => state.routing.location);
   ...
   useEffect(() => {
      ... map init ...
      map.on('moveend', () => {
         console.log(location);
      });
   }, [];

   useEffect(() => {
      console.log(location);
   }, [list of dependencies]);
}

The idea was to register a listener on mapbox recognized action moveend, get the custom location variable (unrelated to mapbox) at that moment from Redux and do something with it. Since only one handler is required, I registered it in the first useEffect that is called only once, but I expected the value location will be fetched every time moveend is triggered.

This is not happening and I wonder why? The location is always the same as it is on page load. Which concept about React/Redux did I get wrong? The location logged in the second useEffect will always be the correct one (one currently in Redux) but that useEffect triggers on dependency change.

Thank you!

ph0enix
  • 763
  • 2
  • 8
  • 23
  • 1
    Does this answer your question https://stackoverflow.com/questions/55565444/how-to-register-event-with-useeffect-hooks? – Lin Du Jul 12 '22 at 10:33
  • Yes! It seems that I was dealing with [stale closure values](https://reactjs.org/docs/hooks-faq.html#why-am-i-seeing-stale-props-or-state-inside-my-function). When I fix it I'll post the answer of a solution here. Thanks. – ph0enix Jul 12 '22 at 12:24

0 Answers0