Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

434
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda