Search code examples
javascriptreactjsreact-hooksclosures

variables used in callback in useEffect are updated despite not being dependencies


  const comp_ref = useRef();
  const { active_page, path_arr, is_active_alert } = useCustomHook();
  const { user_loaded, nav_collapse, mobile } = useSelector(
    (state) => state.boot
  );

  useEffect(() => {
    if (nav_collapse || mobile) {
      if (is_active_alert && comp_ref.current) {
        comp_ref.current.style.transform = "translateY(0px)";
      }
    }
  }, [is_active_alert]);

In the useEffect, it does not have nav_collpase or mobile as its dependencies/triggers.

Both nav_collpase and mobile are redux states that hold merely boolean values.

Based on my testing, it still gets the updated values for both nav_collpase and mobile whenever the callback is run (due to a change in is_active_alert).

Question:

  1. How is the callback in the useEffect able to get the updated values for the state variables when it doesn't depend on them?

Solution

  • How is the callback in the useEffect able to get the updated values for the state variables when it doesn't depend on them?

    • The useEffect hook is called each and every render cycle
    • The callback function is redeclared each and every render cycle, with any new values closed over in scope.

    It's only when the useEffect hook's dependencies change that the callback is actually called, thus seeing whatever the current values are that have been closed over in callback scope.