useContext in useEffect

  • administrators

    If you want to do it right with useEffect, you must ensure all dependencies are used in the second param. What happens if you have context as dependencies, and useEffect also changes the state of context - it will go into the infinite loop.
    Can we more useContext into useEffect? Not directly, because it against the rule of hook.

    Here is the solution using useRef.

      const ssOptionRef = useRef(useContext(OptionContext));
      useEffect(() => {
        const currentOptions = {
          ag: myAg,
          gender: myGender,
          event: myEvent,
          type: myType,
          scope: myScope,
        // this is briliant -
        const [allOptions, setAllOptions] = ssOptionRef.current;
        const newOptions = { ...allOptions, ...currentOptions };
      }, [myEvent, myScope, myAg, myGender, myType]);

    Note that there is no initialization of context when the route changes. The initialization only happens when the page is reloaded.

  • administrators