React Hooks (useState)

Hello everyone, what’s up? Hope all of are you well by the grace of almighty Allah. Alhamdulillah I am also fine by the grace of omnipotent Allah. Today I will discuss React Hooks. We know react has seven hooks without custom hooks. Since the hook is so important, I don't want to discuss it all in one day, today I will just discuss the useState hook. First of all I will discuss What is hook? Then I will discuss useState hooks.

What is hooks?
Hooks is nothing but a simple thing which can handle of react’s state and all others feature without react class. Although Hooks generally replace class components, there are no plans to remove classes from React.

Limitation of hooks:

  • React Hooks has three limitations. There are:
  • You can call hooks only from react function component.
  • You can call hooks only from top level component.Hooks cannot be conditional. You can’t call hooks inside loop, condition, and nested function.

useState
Hook allows us to track state in a function component. Basically state refers our application data that need to be tracking. useState accepts an initial state, that can be different value based on data and returns two values: Current state and function. Basically this two returns value we destructure from useState. Function update the state.

For example:
Firstly we have to import useState from react

import { useState } from "react";

Then destructure the return value from useState in function component

import { useState } from "react";

function FavoriteName () {
const [name, setName] = useState(“ “);
}

The first value users is our current state and the second value setUsers is the function that is used to update our state. These names are variables that can be named anything we would like.
Finally, we set the initial state to an empty string: useState(“ ”). This initial state will be change based on data.

Our state is ready, now we can use it in a component

import { useState } from "react";

function FavoriteName() {

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

return

My name is {name}!

28