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 - https://stackoverflow.com/questions/56240067/accessing-context-from-useeffect
        const [allOptions, setAllOptions] = ssOptionRef.current;
    
        const newOptions = { ...allOptions, ...currentOptions };
        setAllOptions(newOptions);
    
        setSSOptionsCookie(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