title: React Error: Too many re-renders. React limits the number of renders to prevent an infinite loop
body: <p>The code was originally supposed to just display a different greeting using the time of the day (<em>Date().getHours()</em>) and some conditions. However, I tried to simplify the code to just check if the state would change, it gives the same error mentioned above.</p>
  
  <p>The state does get displayed as is if I don't include the conditions setting the state.</p>
  
  <pre><code>import React from 'react'
  import Cards from './cards'
  
  function Main() {
  
      const [greeting, setGreeting] = React.useState("Hello")
      const user = false
      if (user) {
          setGreeting("Welcome")
      } else {
          setGreeting("You dont belong here")
      }
      return (
          &lt;main role="main" className="col-md-9 ml-sm-auto col-lg-10 px-md-4"&gt;
              &lt;div className="d-flex flex-wrap flex-md-nowrap pt-2 mt-2 mb-4"&gt;
                  &lt;h1&gt; {greeting} Random Dude!&lt;/h1&gt;
              &lt;/div&gt;
              &lt;Cards /&gt;
          &lt;/main&gt;
      )
  }
  
  
  export default Main
  </code></pre>
  
  <p>I tried to wrap this in a function as well but no luck which makes sense because every time the code gets rendered, the function is called again and it loops</p>
  
  <pre><code>import React from 'react'
  import Cards from './cards'
  
  function Main() {
  
      const [greeting, setGreeting] = React.useState("Hello")
      const user = false
      function greetingMessage() {
          if (user) {
              setGreeting("Welcome")
          } else {
              setGreeting("You dont belong here")
          }
          return (greeting)
      }
      return (
          &lt;main role="main" className="col-md-9 ml-sm-auto col-lg-10 px-md-4"&gt;
              &lt;div className="d-flex flex-wrap flex-md-nowrap pt-2 mt-2 mb-4"&gt;
                  &lt;h1&gt; {greetingMessage()} Random Dude!&lt;/h1&gt;
              &lt;/div&gt;
              &lt;Cards /&gt;
          &lt;/main&gt;
      )
  }
  
  
  export default Main
  </code></pre>