Unlocking the Power of React Hooks: The useState
Learn how to add state and other functionality to your functional components in React with the powerful useState hook.
Introduction
In the previous blog we discussed what React Hooks are and how to use them effectively.
Hooks allow developers to add state and other functionality to functional components. One of the most commonly used hooks is useState
. In this blog, we will explore what useState
is, why it is useful, how to use it and in the end, we will be creating a basic Form to get familiar with this hook.
What is useState
?
useState
is a hook that allows you to add state to a functional component.
In React, state is an object that holds the data that determines how a component should be rendered.
When the state of a component changes, React automatically re-renders the component, updating the UI to reflect the new state.
How to use useState
?
Now we have gained some knowledge about useState. So let's jump to the fun part i.e code.
useState
returns an array with exactly two items:
The
current state
of this state variable, initially set to the initial state you provided.The
set function
that lets you change it to any other value in response to interaction.
To use useState
, we first need to import it from the React library:
import React, { useState } from "react";
Then, we can declare state in a functional component like this:
function MyComponent() {
const [age, setAge] = useState(10);
//...
In the above example, we declare a state variable called age
with an initial value of 10
. We also declare a function called setAge
that we can use to update the value of age
.
We can then use age
and setAge
in our component to manage state.
For example, we could use them to display the current age and update it when a button is clicked:
In the above example, we define a function called handleButtonClick
that updates the age
state variable by calling setAge
. We then use this function as the onClick
handler for a button that increments the count.
Here's the link to the demo
Let's create a Form
This is an advanced section where we will be learning about how we can use useState
with objects to create a form.
Before jumping into this section you can experiment with the above example we used so that you get to understand this section in a better way.
import React, { useState } from "react";
function SportsForm() {
// ๐ Declare state using useState
const [formData, setFormData] = useState({
name: "",
age: "",
favoriteSport: "",
});
}
In the above snippet, we are declaring the variables we will be using to take inputs from the user. We are using three variables name
, age
and favoriteSport.
Now we will be creating the function which would handle how the states of these variables change when the user changes their value.
// ๐ง Define a function to update the form data state
function handleInputChange(event) {
const { name, value } = event.target;
// ๐ค Update the formData state using setFormData
setFormData({ ...formData, [name]: value });
}
handleInputChange
handles the change of state. One question that might have come to your mind would be "earlier we used a very simple way to update value, but here we are using (...)".
If I was reading this article while starting my journey of learning hooks, then this question would surely have struck my mind.
If an object is contained within a Hook, it cannot be updated directly. If you call the functional updater and pass arguments directly, the values within the Hook will be replaced instead of merged. To ensure merging, we are using a spread operator (โฆ).
Now, we will be creating a function that captures the response when the user clicks on "๐ Submit".
// ๐ค Define a function to handle form submission
function handleSubmit(event) {
event.preventDefault();
console.log(formData);
// ๐ Perform form submission logic (e.g., send data to API or send via email)
}
Here's the complete code:
Conclusion
useState
is a powerful hook that allows us to add state to functional components in React.
By using useState
, we can write simpler and more maintainable code, and create components that are interactive and responsive to user input.
I hope this introduction to useState
has been helpful, and you feel more confident using this hook in your own React projects!
Will meet you in the next one. Till then keep on practicing.
Whenever you are ready there are 2 ways I can help you:
sideProjectss: Create you personal page showcasing your side projects in just 5 mins
HTML email: Create your marketing HTML emails using AI within seconds