-1

I can't seem to figure out why this piece of React code isn't console logging any of the values...

  const [href, setHref] = useState("");
  const [whatever, setWhatever] = useState("");

  useEffect(() => {
    setHref(window.location.href);
    setWhatever(href + " cats");

    console.log(whatever);
    console.log(href);
  }, []);
evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
za1234ki
  • 105
  • 1
  • 9

1 Answers1

0

It prints nothing because you can not access new state immediately after you update state - state is accessed from closure and closure is recreated only after element rerenders. Since your effect is executing only once there is no way you can log new state within effect, move console log out of the effect and you will log fresh values after each rerender.

Milos Pavlovic
  • 1,355
  • 1
  • 2
  • 7