4 Different Examples of the useState Hook in React

<p><code>useState</code>&nbsp;is a widely used hook in React. Almost every component you develop in React involves state. In this post, I am going to show you four different use cases of the&nbsp;<code>useState</code>&nbsp;hook.</p> <p>I am assuming you have a basic knowledge of React and state. If not, visit the&nbsp;<a href="https://reactjs.org/docs/getting-started.html" rel="noopener ugc nofollow" target="_blank">docs</a>&nbsp;to get started.</p> <h1>Initializing State</h1> <p>As a reminder, I&rsquo;ll go over how to initialize state. First, import&nbsp;<code>useState</code>&nbsp;and then, declare your state variables in the following way.</p> <pre> import { useState } from &#39;react&#39;const [name, setName] = useState(&#39;kunal&#39;)</pre> <p><code>setName</code>&nbsp;is the function used to set the state i.e.&nbsp;<code>name</code>. It has a default value.</p> <p>Do not set state directly, always use the function. Read&nbsp;<a href="https://medium.com/analytics-vidhya/why-we-should-never-update-react-state-directly-c1b794fac59b" rel="noopener">this</a>&nbsp;to know why.</p> <p>Now, let&rsquo;s go over some use cases.</p> <h2>1. Conditional Rendering</h2> <p>Let&rsquo;s say your application has a user and you want to display something based on whether the user is an admin. You can do that with conditional rendering.</p> <p>In this example, we have a set of records that all users can see. But, an admin user has the option to edit each record. First, define the user as state.</p> <p><a href="https://levelup.gitconnected.com/4-different-examples-of-the-usestate-hook-in-react-5504ce011a20">Website</a></p>