title: React state not updating correctly
body: <p>I have a usecase where I want to call an API at a regular interval until API returns a response saying not to reload further. Following is my code.</p>
  <pre><code>  const [username, setUserName] = React.useState();
    const [reloadEstimates, setReloadEstimates] = React.useState(true);
    const [estimates, setEstimates] = React.useState([]);  
    const [progress, setProgress] = React.useState(true);
    const [showError, setShowError] = React.useState(false);
    const [errorMessage, setErrorMessage] = React.useState();
    useEffect(() =&gt; {
      const token = jwt(Cookies.get('id-token'));
      const username = token[&quot;cognito:username&quot;]
      setUserName(username)
    
  
      async function fetchData() {    
        let allestimates = await fetch(&lt;api-url&gt;, {
                  //mode: 'cors',
                  method: 'GET',
                  headers: new Headers({'Authorization' : 'Bearer ' + Cookies.get('id-token')})
                })
              .then(res =&gt; {
                  if(res.ok) {
                    return res.json();
                  }
                  throw new Error(`API call failed: ${res.code} - ${res.message}`);
              })
              .catch(er =&gt; { setShowError(true); setErrorMessage(`API error: ${er}`); } );
  
              //console.log(allestimates)
        
        
        return allestimates;
      }
  
      
  
    async function refreshEstimate() {
      console.log(&quot;checkpoint1&quot;);
      console.log(reloadEstimates);
      if (reloadEstimates === true){
          fetchData().then(
            allelatimates =&gt;{ 
              setEstimates(allelatimates.estimates);
              console.log(allelatimates )
              console.log(allelatimates.reload )
              if(allelatimates.reload === 'NOT RELOAD'){
                
                console.log(&quot;checkpoint2&quot;);
                return false;
              }
              return true;
            }
              
        ).then((r)=&gt;{console.log(r);setReloadEstimates(r); console.log(reloadEstimates)}).then(()=&gt;setProgress(false));
      }
      else{
        console.log('No need to fetch.')
      }
    }
  
      var refreshInterval = setInterval(() =&gt; {
          refreshEstimate();
      }, 10000);
    },[]);
  
  </code></pre>
  <p>I don't know why but <strong>setReloadEstimates(r)</strong> does not convert state <strong>reloadEstimates</strong> to false. And it keeps on running. Following is the console output. Please let me know what i am missing or is there another way to achieve this. Thanks.</p>
  <p><a href="https://i.stack.imgur.com/NZkA4.png" rel="nofollow noreferrer">enter image description here</a></p>