Learn React useState Hook

Hooks are a new addition to React 16.8. It enabled the use of state inside functional components. Hooks are functions that enable functional components to attach(Hooked into) with react state and use react lifecycle features.

Easy Peasy useState() Hook

Just as a start you can keep in mind that state is a kind of internal memory to store data related to the component. And that memory is preserved even after re-rendering

Let’s have a look at the first react hook which is useState hook.

First, import the useState Hook at the beginning of the file. We can import it directly from react using the below code.

import React, { useState } from 'react';

And now we can use the imported useState hook.
Let’s Declare a new state variable inside the function component using useState Hook. See the code below

const [name, setName] = useState("Initial name");

You can see the useState has returned two values name and setName. And also you can see useState has consumed a string value as well.

Let’s see what are the two values returned and the use of the two values.

1- First the current state value(name).
2- Second, a function to update the current state value(setName).

Accessing the two values is done using the array Destructuring syntax method. We can define any name for the first and second values. Here I have used nameand setName. You can give any suitable name when accessing useState based on your program use case.

Leave a Reply

Your email address will not be published. Required fields are marked *