title: Conditionally call useState hook in react
body: <p>My question is really simple. I want to call the <code>useState</code> hook conditionally. I know this is not allowed in react, and that is why I'm here.</p>
  <p>My use case is: I have an array of &quot;comments&quot;. For each comment, I want to allow it to be liked based on whether the user is logged in or not. For this, I am using a <code>hasLiked</code> state. Now the problem is that if the user is not logged in, then this state is redundant and I don't want it.</p>
  <p>Here is the code to make it clearer:</p>
  <pre><code>export default function Comment() {
      const isLoggedIn = someAuthAPI();
      const [hasLiked, setHasLiked] = useState(false) // this is the line that I want to call conditionally
      // ...
      return &lt;div&gt;...&lt;/div&gt;
  }
  </code></pre>
  <p>I want to do this:</p>
  <pre><code>export default function Comment() {
      const isLoggedIn = someAuthAPI();
      if (isLoggedIn){
          const [hasLiked, setHasLiked] = useState(false) // this is obviously not allowed and will throw an error
      }
      // ...
      return &lt;div&gt;...&lt;/div&gt;
  }
  </code></pre>
  <p>I searched for a solution but could not find anything useful. Most answers are either outdated or suggest using a third party library.</p>
  <p>To reiterate, I just want to know if there is a way to make a state conditionally defined. I know I can do</p>
  <pre><code>const [hasLiked, setHasLiked] = useState(isLoggedIn ? false : null) // or undefined
  </code></pre>
  <p>but that is not I want here. I want to prevent the hook call altogether. This is because the example that I have taken here may not use much memory, but what I am using it for is quite memory demanding.</p>