4 Different Examples of the useState Hook in React
<p><code>useState</code> 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 <code>useState</code> hook.</p>
<p>I am assuming you have a basic knowledge of React and state. If not, visit the <a href="https://reactjs.org/docs/getting-started.html" rel="noopener ugc nofollow" target="_blank">docs</a> to get started.</p>
<h1>Initializing State</h1>
<p>As a reminder, I’ll go over how to initialize state. First, import <code>useState</code> and then, declare your state variables in the following way.</p>
<pre>
import { useState } from 'react'const [name, setName] = useState('kunal')</pre>
<p><code>setName</code> is the function used to set the state i.e. <code>name</code>. It has a default value.</p>
<p>Do not set state directly, always use the function. Read <a href="https://medium.com/analytics-vidhya/why-we-should-never-update-react-state-directly-c1b794fac59b" rel="noopener">this</a> to know why.</p>
<p>Now, let’s go over some use cases.</p>
<h2>1. Conditional Rendering</h2>
<p>Let’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>