Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

433
Visualizações
Use nextjs routing outside react hooks in regular javascript

I have a NextJS app. I want to add a function that can redirect to any page using nextjs routing.

For example, after finishing signup I want to redirect to a certain page.

If I create this function (reusable everywhere) :

import { useRouter } from 'next/router'

const goTo = (href) => {
  const router = useRouter()
  router.push(href)
}

I want to add this to my signup Logic, the problem is that I break React Hooks rules :

react-dom.development.js?ac89:14906 Uncaught (in promise) Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

And effectively useRouter is a React Hook, and I'm trying to call it outside a React function, as stipulated here https://reactjs.org/docs/hooks-rules.html it will not work.

How can I then have a routing solution for NextJS to be callable in regular Javascript ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

So If you're using purely React.js (without Next.js on top of it), you can simple do it this way:

 Import React from 'react' 

export const handleRoutes = (url) => {
 const history = React.useHistory() 
return history.push(url)

}

Then You'd import this regular js function in any of your react files, like this:

import { handleRoutes } from 'fileName.js'

<button onClick={()  => handleRoutes("/routeToBeRedirectedTo")}> Click to redirect </button>

However when using Nextjs I'm not sure that the above way would work. My personal method would be simply implementing this function (in a utility.js file):

export const handleRedirect = (router, url) => {
 return router.push(url)} 

Then just importing the function & useRouter hook in the file you want:

import { handleRedirect } from "./utility.js"
import { useRouter } from "next/router" 

const router = useRouter

Then inside your JSX return statement:

<button onClick={()  => handleRedirect(router, "/routeToBeRedirectedTo")}> Click to redirect </button>

And if it's a redirect after sign in/sign up, just simply useEffect like so:

// depends if you're storing your user credentials in your local storage or cookies, this example below would be if your User credentials are stored in localstorage 
const user = JSON.parse(localstorage.getItem("user"))

UseEffect(() => {
 if (user) return handleRedirect(router, "/routeToBeRedirectedTo")
}, [user]) 
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda