1

I have a component which once once it rendered I need to redirect a user to another path and I'm using useEffect hook of react but it's getting rendered over and over and over without stopping:

const App: FunctionComponent<{}> = () => {
const [message, setMessage] = useState("");

  useEffect(() => {
    if (condition) {
      setMessage("you are being redirected");
      setTimeout(() => {
        location.href = `http://localhost:4000/myurl`;
      }, 2000);
    } else {
      setMessage("you are logged in");
      setTimeout(() => {
        <Redirect to={"/pages"} />;
      }, 2000);
    }
  }, [message]);

  return (
    <>
      {message}
      <BrowserRouter>
        <Route exact path="/login/stb" render={() => <Code />} />
      </BrowserRouter>
    </>
  );
};

export default App;
skyboyer
  • 22,209
  • 7
  • 57
  • 64
Errand
  • 121
  • 9

1 Answers1

1

It looks like setMessage is setting a message state variable in the component. This occurs during every run of useEffect. State changes will cause your component to rerender.

Basically, the flow causing the loop is this:

  1. Initial component render
  2. useEffect is run
  3. message state is updated
  4. Component rerenders due to state change
  5. useEffect is run as it's trigged on message change
  6. Back to step 3

If you want useEffect to only run on initial render, and redirect after a user has logged in, you could change it to something like this:

  const [loggedIn, setLoggedIn] = useState(false);

  useEffect(() => {
    if (someConditionHere) {
      setLoggedIn(true);
  }, []);

  return (
    loggedIn ? <Redirect to={"/pages"} /> :
    <BrowserRouter>
      <Route exact path="/login/stb" render={() => <Code />} />
    </BrowserRouter>
  );

I don't know everything about the setup, so that's simplifying and making some assumptions.

Charlie Dobson
  • 123
  • 2
  • 9