A guide to use useState Hook

A guide to use useState Hook

useState is a Hook that allows you to have state variables in functional components.

There are two types of components in React: class and functional components.

Class components are ES6 classes that extend from React.Component and can have state and lifecycle methods :

class.jpg

Functional components are functions that just accept arguments as the properties of the component and return valid JSX:

fn.png

As you can see, there are no state or lifecycle methods. However, since React 16.8 we can use Hooks, which are functions with names starting with use, to add state variables to functional components and instrument the lifecycle methods of classes.

Importing useState

You can import useState from react using :

import {useState} from'react' ;

The useState Hook allows you to declare only one state variable (of any type) at a time, like this:

const [message,setmessage]=useState("")

During the initial render, the returned state (state) is the same as the value passed as the first argument (initialState).

useState takes the initial value of the state variable as an argument. It returns an array where the first element is the state variable and the second element is the function to update the state variable .

Here , in the above example message will be initialised with empty string . setmessage is used to set the value of the message . Basically you can it call it as a setter function in other languages .

Updating State

The second element returned by useState is a function that takes a new value to update the state variable.

setMessage(e.target.value)

The above code will update the value of the message to the target value .

Conclusion

useState is a Hook (function) that allows you to have state variables in functional components.

You pass the initial state to this function, and it returns a variable with the current state value (not necessarily the initial state) and another function to update this value.