Component-updating Custom Hook in UseEffect

I have the following code:

function checklogin(callback) {
  if (!state.user.authenticated) 
    pushhistory("/accounts/login", function(){teamhome2_message();});
  else 
    callback();
}

// ATTEMPTED HOOK VERSION

function useLogin(state, url, loginMessage) {
  const history = useHistory();
  if (!state.user.is_authenticated) {
    history.push(url);
    loginMessage();
    return false;
  }
  return true;
}

Functions that go along with it:

function pushhistory(url, callback) {
  history.push(url); // hook from react-router (const history = useHistory())
  callback();
}
function teamhome2_message() {
  const info = message.error({
    key: "apihome2",
    content: "Log in to access team data!",
  });
};

My usage:

useEffect(() => {
  checklogin(function() {
    // the following two are valid functions, but i didn't
    // paste them here because they're kinda long
    checkauth(function() {
      checkteamexists(teamname);
    })
  })
}, []);

It’s obvious that I can’t rewrite checklogin as a hook because I am using the initial checklogin function inside useEffect. However, I can’t place the hook of checklogin outside of useEffect because checklogin performs a component update by redirecting to /accounts/login.

So now I’m stuck: if I place the hook version of checklogin inside of useEffect, it will violate the rule of hooks. If I place it outside of useEffect, React will throw this error:

enter image description here

How can I write a checklogin hook while not violating the rule?

Can anyone please help? Thanks in advance.

Answer

I think the solution is to move the useEffect call inside the useLogin hook, like so:

function useLogin(state, url, loginMessage) {
  const history = useHistory();
  const loggedIn = state.user.is_authenticated;
  useEffect(() => {
    if (!loggedIn) {
      history.push(url);
      loginMessage();
    }
  }, [loggedIn]);
  return loggedIn;
}