DEV Community

Cover image for Using Hook inside initialize state function() in useReducer() Hook
SPeshov
SPeshov

Posted on

Using Hook inside initialize state function() in useReducer() Hook

So I had this issue with using Hook inside Initialize Function of react useReducer Hook, as a third argument to it.

And the problem is that I was getting


    Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. You can only call Hooks at the top level of your React function.
Enter fullscreen mode Exit fullscreen mode

The problem is that i was using Hook inside of Initialize function of useReducer Hook

And it took me a while to find where I was getting this from.

As a solution I tried to pass that hook value that Im trying to get inside of Initialize function directly from the functional component where I use the useReducer hook but it turns out that init function only accepts only one argument so that was a bummer 🙃 .

My simple and time saving solution was just to get rid of the init function and set try to determine initial state directly in my functional component and that worked just fine

Before

    export const InitState = (initialState) => {
      const hookMeUp = useMyHook(); // <- PROBLEM

      return {
        ...initialState,
      yyy: hookMeUp.yyy,
      };
    };

    export const FunComp = ()=>{
    const initialState = {
        xxx: 1,
            yyy: 2,
      };

    const [state, dispatch] = React.useReducer(MyReducerFun, initialState, InitState);

    ...aaand so onnn...
    }
Enter fullscreen mode Exit fullscreen mode

After

    export const FunComp = ()=>{

    const hookMeUp = useMyHook();
    ****
    const xxx =  hookMeUp.xxx;
    const yyy =  hookMeUp.yyy;


    const initialState: MyStateType = {
    xxx,
    yyy
      };

      React.useEffect(() => {
        const onResizeCallBack = () => dispatch({ type: "onResize" });
        window.addEventListener("resize", onResizeCallBack);
        return () => window.removeEventListener("resize", onResizeCallBack);
      });

      const [state, dispatch] = React.useReducer(MyReducerFun, initialState);

    ...aaand so onnn...
    }
Enter fullscreen mode Exit fullscreen mode

links:

Top comments (0)