React Hooks. How to use updated state immediately

I just started learning about hooks, and I’m curious how I can access a recently updated state? See code below.

const [name, setName] = useState('jimothy');

  function handleClick() {
    setName(() => 'timothy');
    console.log(name);
    consoleName();
  }

  function consoleName() {
    console.log(name);
  }

I have the function handleClick() attached to a button. Both consoles in this circumstance, on the first click, still console jimothy. I’ve been doing some reading and as I understand it, it’s due to how React batches the information.

I read a few articles about using useEffect() to use the most updated state, I was curious if that was the simplest/only way to do it? seemed a little easier in Class Components using setState() to accomplish this, but maybe I’m missing something?

scroll down this article to Troubleshooting section. The very first case will be about your question

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.