React Hooks are a powerful and easy-to-use feature that allows developers to write and manage state and side-effects in functional components. In this blog series, we’ll take a deep dive into the most commonly used hooks and explore how they can be used to simplify your code, improve performance, and make your React applications more efficient.
From the basics of useState
and useEffect
to more advanced hooks like useContext
and useReducer
, we'll provide real-world examples and explanations to help you master this essential tool in the React developer's toolbox.
In this blog we will be keep our focus on useState
hook. Let’ start…
useState
is used to store the information which can change later.
For example,
const [counter, setCounter] = useState(0);
The state variable i.e counter stores the value you provided.
The state setter function i.e setCounter is used the change previously stored value.
we have initialized the counter with 0 while declaring the state.
const [ stateVariable, stateSetterFunction] = useState(iniyialValue);
This is how we declare the state using useState
every time.
Let’s build a small counter component:
import React, { useState } from 'react';
function CounterApp() {
// Declare a new state variable, which we'll call "count"
const [counter, setCounter] = useState(0);
return (
<div>
<p>You clicked {counter} times</p>
<button onClick={() => setCounter(counter + 1)}>
Click me
</button>
</div>
);
}
What we have done here?
Every time user click on the Click me
the counter value get incremented by one and reflecting it. The setCounter
takes previous value of counter
and add the one in it.
The onClick
function takes a function and on every click the setCounter function increments the counter value. The change in state initiates new render which updates the value of counter
.
useState
supports wide area of data types. Such as, Numbers, Boolean, Array, Objects, String , ect.
How useState works in background:
React is based on components and for every component there is object which is working in the background.
This object contains a array state cell
which store the state and pointer to point the current state. This pointer helps use to check for the previous state.
As we call useState
, React stores the new state in next available state and moves the pointer to it.
A simple Login form component:
We have created the isLogedIn
state for keeping tract of user login status.
Another state user
is an object which contains the userId and password.
To update the state we need to careful as we need to provide the previous state as a object. This can be done by using the spread operator.
import { useState } from "react";
export default function Logout() {
const [isLogedin, setIsLogedIn] = useState(false);
// This state is handling the used is loged in or not
// We have initialized this by using the false as we want to check if use is login or not
const [user, setUser] = useState({
userId: "",
password: ""
});
//We have used object to initialize the object
//Using this type we can create only state and access it,
//the updation of state is different that previous one.
const handleSubmit = (e) => {
//This function get called after submitting the call
e.preventDefault();
console.log(user.userId + " " + user.password);
setIsLogedIn(true);
};
const handleOnChange = (e) => {
e.preventDefault();
setUser({
// The set method for the user state
...user, //This is the spread operator which spreds the previous user value i.e userId and password
[e.target.name]: e.target.value // now new updated values are updated for the same
});
};
return (
<div>
<form onSubmit={handleSubmit}>
userid :{" "}
<input
name="userId"
value={user.userId}
type="text"
onChange={handleOnChange}
/>
<br />
password :{" "}
<input
name="password"
value={user.password}
type="password"
onChange={handleOnChange}
/>
<br />
<input type="submit" />
</form>
</div>
);
}
In conclusion, the useState
hook is an essential tool for managing state in React functional components. With its easy-to-use syntax and intuitive behavior, useState
makes it simple to create and update state, even in complex applications.
We've covered the basics of how the hook works and some best practices for using it effectively, but the possibilities are endless. As you continue to work with React and build more complex applications, you'll find that useState
becomes an indispensable tool in your developer's toolbox.
Thank you for reading this article and I hope it helped you understand how to effectively use useState hook. Please also read the next part of the hooks here.
Thank you for reading the blog, follow for more.
LinkedIn — https://linkedin.com/in/joshiomkar04
Twitter — https://twitter.com/ye_joshya