Next.js Discord

Discord Forum

Client component: redirect or useRouter?

Answered
Greenish Elaenia posted this in #help-forum
Open in Discord
Greenish ElaeniaOP
Just watched NextJS VP's youtube video about common mistakes in NextJS and he talked about how using redirect in a client component to navigate to another page programmically was a mistake and that the better solution is to use useRouter();
My component currently uses redirect to do this, with no errors being thrown.
I'd like to ask what the difference is between the two in this case.
Answered by Ray
action props should work
View full answer

16 Replies

Sun bear
was he talking about the "redirect" function from next or the concept of "redirecting" ie. using something like window.location =
the next redirect function can only be called in server components
Western paper wasp
The redirect() function from next/navigation can only be used in server components / route handlers / server actions. useRouter() is not valid in any of these places. So there’s no situation in which you could choose between useRouter and redirect().
On the client, useRouter().push(...) is preferred to other approaches because it performs a SPA navigation, which is faster than a “full” navigation, because the latter would reload the full page
Greenish ElaeniaOP
I'm not sure why but this component says 'use client' at the top but was using redirect(/) with no errors previously
@Greenish Elaenia I'm not sure why but this component says 'use client' at the top but was using redirect(/) with no errors previously
redirect() throw an error and it will redirect if the ErrorBoundary is able to catch the error. if you use redirect() inside the component body or useEffect() it will work. However, if you use it in event handler (eg, onClick, onChange), it doesn't work
Greenish ElaeniaOP
The redirect is in a form action ={handleSubmit}, async function handleSubmit(formData: { get: (arg0: string) => any; }) {
Answer
onSubmit shouldn't work
Greenish ElaeniaOP
got it
Greenish ElaeniaOP
Actually I just restarted the computer and it no longer works
Can't do useRouter there. It will throw a too many react error
Currently not at computer, will share error screencap in a second
German Hound
is there any way i can use a redirect function in client components right now iam using window.location.href is there any alternative of it and also i see a small splash before redirect can anyone help
German Hound
thank you i created one