0

I'm trying to update the state inside useEffect hook but the state is not updating

const [course, setCourse] = useState("loading");

  useEffect( () => {

    const fetchData = async () => {
        await setCourse("m");
        console.log(`setCourse ${course}`);

    };

    fetchData();

  }, []);

While printing in console it is showing loading but I want to print "m".

Dhiraj Baruah
  • 192
  • 1
  • 8
  • Does this answer your question? [React setState not Updating Immediately](https://stackoverflow.com/questions/38558200/react-setstate-not-updating-immediately) React state updates are asynchronous, so this will ***only ever*** log the state value from the current render cycle. This question is asked nearly daily, please try to search for answers before asking. – Drew Reese Jun 16 '20 at 05:39
  • Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) You cannot await a state update as the whole function needs to rerender for that state change to happen. – John Ruddell Jun 16 '20 at 05:40
  • @DrewReese that is `setState` instead of the hook form `useState` :) – John Ruddell Jun 16 '20 at 05:41
  • 1
    @JohnRuddell React component state is... react component state. :) The reason is exactly the same. – Drew Reese Jun 16 '20 at 05:42
  • True, but the information around why a class vs a hook update is relevant. (closures... etc.) Time is a factor in hooks – John Ruddell Jun 16 '20 at 05:45

0 Answers0