React Router Docs & Redirect vs history.push()

Viewed 952

I've tried to read previous answers but unfortunately they only created more questions. In react router docs https://reactrouter.com/web/example/auth-workflow on line 124 after signout they use history.push("/")

What's the purpose of history.push() here and why not use Redirect instead?

1 Answers

Redirect is more of a component which you render in case some logic exists or does not exists, consider following example, it is generally used when you have some logic on route and want to do conditional redirection.

Similarly, you use history.push when you have some event triggered action, like you click on a button, which in turn does some validation and then might re-direct you based on your business logic.

I have given examples for both the cases, hope it helps.

const Admin = () => {
  const [isInvalidUser, setUserInvalid] = useState(false);  
  
  useEffect(() => {
    // check if valid user via API call
    setUserInvalid(true);
  }, [])
  
  // here you are returning a component in form of Redirect
  // this is automatically executed when you open a particular route, it is not event triggered
  if(isInvalidUser) {
    return <Redirect to="/auth" />;
  }

  return <AdminView />;
}

const Login = () => {
  
  const handleLogin = () => {
   
    // business logic to validate login
    if(validUser) {
      // you cannot have return statement here with Redirect as this is a handler
      history.push("/home");
    }
  
  }
  
  // assume you have state for username and password
  return (
    <button onClick={handleLogin}>Submit</button>
  );

}

You can use whichever you need based on your use case and approach.

Related