0

I am trying to set a state variable using useState hook and then access(console.log) it inside a useEffect hook in a reactjs app. And also I displayed the value of state variable on front end. But the problem is that the state variable's value is displaying correctly on front end but undefined in console. Actually I want to set the state variable and access it inside the same useEffect hook. How to solve this?

  const [localusername, setlocalusername] = useState();
  const [localpassword, setlocalpassword] = useState();
  useEffect(() => {
    setlocalusername(localStorage.getItem("username"));
    setlocalpassword(localStorage.getItem("password"));
    console.log(localusername);
    console.log(localpassword);
  }, []);

Here is the attached snapshot of console...

  • I recommend to use an initializer function to initialize your state. `const [localusername, setlocalusername] = useState(() => localStorage.getItem("username"));` and if you need to know what the initial value is set to for debugging you can just `console.log(localusername)` as the next line and it will show you the current value alright. – Martin Feb 14 '23 at 08:08

1 Answers1

2

If you want to get new values of any vars, like useState you must to subscribe it using useEffect. For example:

      useEffect(() => {
        setlocalusername(localStorage.getItem("username"));
        setlocalpassword(localStorage.getItem("password"));
      }, []);

      useEffect(() => {
        console.log(localusername);
        console.log(localpassword);
      }, [localusername, localpassword])
Nikita Aplin
  • 367
  • 2
  • 10