4 Different Examples of the useState Hook in React

useState 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 useState hook.

I am assuming you have a basic knowledge of React and state. If not, visit the docs to get started.

Initializing State

As a reminder, I’ll go over how to initialize state. First, import useState and then, declare your state variables in the following way.

import { useState } from 'react'const [name, setName] = useState('kunal')

setName is the function used to set the state i.e. name. It has a default value.

Do not set state directly, always use the function. Read this to know why.

Now, let’s go over some use cases.

1. Conditional Rendering

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.

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.

Website