Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using dispatch as custom hook dependency re-renders hook repeatedly #51

Closed
painedpineapple opened this issue Oct 14, 2019 · 3 comments · Fixed by #52
Closed

Using dispatch as custom hook dependency re-renders hook repeatedly #51

painedpineapple opened this issue Oct 14, 2019 · 3 comments · Fixed by #52

Comments

@painedpineapple
Copy link

I have this custom hook that utilizes dispatch and has it listed as a dependency. Doing this causes the hook to re-run repeatedly when used inside component.

Custom hook:

let useFetchItbs = () => {
  let dispatch = Store.useDispatch();

  React.useCallback1(
    () => {
      dispatch(SetFetchItbsStatus(Loading));
      Js.Promise.(
        Itb.fetchItbs()
        ->then_(
            response => {
              switch (response) {
              | Ok(response) =>
                dispatch(SetItbs(response.data));
                dispatch(SetFetchItbsStatus(Success()));
              | Error(_error) =>
                dispatch(
                  SetFetchItbsStatus(
                    Failure(
                      "There was a problem retriving ITBs at this time.",
                    ),
                  ),
                )
              };
              resolve();
            },
            _,
          )
        ->catch(
            error => {
              Js.log(error);
              dispatch(
                SetFetchItbsStatus(
                  Failure("There was a problem retriving ITBs at this time."),
                ),
              );
              resolve();
            },
            _,
          )
      )
      ->ignore;
    },
    [|dispatch|],
  );
};

Hook being used:

  let fetchItbs = ItbListsStoreHooks.useFetchItbs();

  React.useEffect1(
    () => {
      fetchItbs();

      Some(() => ());
    },
    [|fetchItbs|],
  );

Note that when I use useCallback0 instead of useCallback1 and remove dispatch as a dependency of the hook, it only runs once as expected.

@MargaretKrutikova
Copy link
Collaborator

Oh, yes, I looked at the implementation real quick and noticed that it is not memoizing dispatch, so every time you use useDispatch, a new function is created. I will prepare a fix for this 😄

@painedpineapple
Copy link
Author

Thank you :)

@MargaretKrutikova
Copy link
Collaborator

Published in v2.0.1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants