Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!