useState in React

useState is a React Hook. It enable you to add state functionality of class component in function component.

Before getting started with useState you should have some understanding about what state and hooks are.

So I will start with State.

State

Just like we have objects for class item which contains properties of that class, Similarly state is an instance of React component class. It holds properties of a react component and React component behaves accordingly when the state changes. In React component is dependent on state , it contains data and information about the component and it can change over time or by user actions and the component behaves accordingly. Which makes react component dynamic.

Hooks

Hooks are basically used in function based components. To get the functionality of state in function components just like class based components we can use useState hook.

useState hook

The useState function is a built in hook. It allows you to add state to your functional components. Using the useState hook inside a function component, you can create a piece of state without switching to class components.

Declaring state in React

Using useState we can declare only one state variable at a time. But a functional component can have multiple state variables for different purpose.

First we will import useState from react package

 import React, { useState } from 'react';

Now declare state variable

const [message, setMessage] = useState(‘Hello’);

message -> state variable

setMessage -> function used to set state variable

useState(‘’) -> takes the initial value of the state variable as an argument