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

131
Vistas
Nextjs UseEffect is not rendering on route change

I am having problem with a useEffect inside a component which is in every component. I have made some authentication and redirects in that component but I figured that when I use Nextjs link or the go back button from the browser, the Layout useEffect is not re rendering which means it is not checking if the user is logged in for example.

here's my layout component

const Layout = ({ children }) => {

  const router = useRouter()
  const { setAuthenticated, userFromDB, setUserFromDB, setIsVender, isVender } = useContext(AuthContext)

  //cuando hacemos un login el token se guarda en el local storage asi que comprobamos que exista
  useEffect(() => {
    const checkToken = async () => {
      const token = localStorage.getItem('FBIdToken')
      if (token) {
        const decodedToken = jwtDecode(token);
        //si la fecha de expiracion del token supero a la actual, redirect al login
        if (decodedToken.exp * 1000 < Date.now()) {
          setAuthenticated(false)
          router.replace('/login');
        } else {
          if(!userFromDB){
            const user = await getUser(decodedToken.user_id);
            //si encontro un usuario, lo asignamos al context api
            if(user){
              console.log(user)
              //  obtenemos el objecto con los datos del usuario y seteamos en el context si es vendedor o no
              if(typeof user.isVender !== undefined){
                user.isVender ? setIsVender(true) : setIsVender(false);
              }
              setUserFromDB(user);
            }
            setAuthenticated(true)
          }
        }
        console.log('ejecutando');
      } else {
        if(router.pathname !== "/" && 
            router.pathname !== "/download-app" && 
            router.pathname !== "/register" && 
            router.pathname !== "/login"
          ) {
          console.log(router.pathname, 'redirigiendo')
          router.replace('/login')
        }
        
      }
    }
    //comprobamos que haya un token y redirigimos al usuario en base a el
    checkToken();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isVender])


  return (
    <div>
      {children}
    </div>
  )
}

this is how I import it inside the _app.js component

  return (
    <AuthProvider>
      <Layout>
        <Component {...pageProps} />
      </Layout>
    </AuthProvider>
  )
}

I hope you can help me, thanks in advance!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

If you want useEffect to trigger on router changes, you must add it as a dependancy of your useEffect hook:

useEffect(() => {
   ...
}, [isVender, router.pathname])
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