Home > Enterprise >  How can I redirect in React without executing more code?
How can I redirect in React without executing more code?

Time:08-21

When I go to the /bar route, I check if the redux state is Null.

If Null, I want to redirect immediately and not withing 1-3 seconds.

Without running the code afterwards, because it would throw errors if redux states are Null

/bar

function Test() {
  const reduxState = useSelector((state) => state.user);

  useEffect(() => {
    if (reduxState.username === null) Router.push('/');
    return () => {};
  }, []);


  console.log('This will get console logged');
   ...

CodePudding user response:

If you are using react router you can use the Redirect component

if(!reduxState.username){
  return <Redirect to='wherever' />
}
return{
  <div>
    //whatever goes here
  </div>
}

CodePudding user response:

If you are using react router dom you can use the useNavigate component

const navigate = useNavigate();

if(!reduxState?.username){
    return navigate("/")
}

CodePudding user response:

In next js you should use the useRouter hook

import { useRouter } from 'next/router'

function Test() {
  const reduxState = useSelector((state) => state.user);
  const router = useRouter();

  if(!reduxState.username){
    return router.push("/");
  }
  return (
    <div>...</div>
  )
}
  • Related