Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

setState not firing in useEffect for Next.js

I’m using next.js and have the following code on the client side.

import { useContext, useEffect, useState } from "react";
import Link from "next/link";
import { UserContext } from "../context";
import { useRouter } from "next/router";

const Nav = () => {
    const [current, setCurrent] = useState("TEST");
    const [state, setState] = useContext(UserContext);
    const router = useRouter();

    // Check first if we are running client side (vs server side)
    // If so, then set state to the pathname. Update on change
    useEffect(() => {
        console.log("router.asPath ", router.asPath);
        console.log("window.location.pathname is ", window.location.pathname);
        console.log(typeof window !== "undefined");
        if (typeof window !== "undefined") {
            console.log("this ran before");
            setCurrent(router.asPath);
            console.log("this ran after");
            console.log("current is ", current);
        }
    }, [typeof window !== "undefined" && window.location.pathname]);
...

I get the following in the console…

router.asPath  /register
window.location.pathname is  /register
true
this ran before
this ran after
current is TEST

I can see that each console.log() is firing in useEffect and returning all the correct values. But setCurrent() doesn’t appear to fire. Why?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

when the code finshes running react will check if there was a state update and if so, only then the value of the useState hook is updated and this leads to a new render in which the new value is availabe so the new data is displayed in the ui.

const [example,setExemple] = useState("")
//...
const newValue = "new"
setExample(newValue);
console.log(example)// output "" and this is normal

so if you want to see the new value of the state it’s not possible from where you are logging because the component didn’t rerendered yet, however since updating state leads to a new render console.log like this from JSX to understand better what’sgoing on:

<div className="App">
  {console.log("this is a new render and this is my current : ",current)}
  //...
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading