In react, use state
hook plays an important role in the development of applications. If you want to add interactivity to your program/components and deal with data in the components we have to use this state hook. It's not just useful; it's really impressive. So, if you're new to React, like me, let's simplify this hook and break it down together.
What is this useState?
Before we dive into useState
, let’s understand what it is. As I mentioned earlier, it's a hook in React. These hooks are like special functions that enable your components to work with and manage data seamlessly. They're called "hooks" because they provide a way to attach functionality to your components, which will make it easy for you to use react by making the code less hard.
But how do they make it easy? let's see how to use this with an easy example here,
Import React and
useState
: First, we need to import React and theuseState
function into our component.
import React, { useState } from 'react';
Define Component Function: In this example, I am gonna name the function as
Counter
as we are doing a simple counter component.Using
useState
: Now, let’s get into action by usinguseState
. Inside our component, we can use theuseState
function to set the state for our counter. This function consists of two parts:
A Variable to Hold the Current State Value: Named
count
in our case, this variable stores the current count value.A Function to Modify the State Value: Named
setCount
, this function is responsible for updating thecount
variable with a new value.
Here's how it looks in the code:
const [count, setCount] = useState(0);
The const
keyword makes count
a constant variable. This means, that once we have set its initial value (in this case, 0), we cannot change it. The function, setCount
, to modify the value stored in the count variable. So, when we use count
we get the current value of the state, and when we use setCount
we change or update that value.
Now, we understand how useState
is used to manage data in a component, I have an idea 💡 the blog I am writing uses useState
(hopefully) for updating likes and some other features. So, why can’t we take this example a step ahead by transforming this simple counter into something you'd find on a blog post —a component for tracking the number of likes?
Let’s wait no more.
So, let’s create the like feature where users click a button on our blog post, by using useState
in the component.
As we did before, let’s start by creating the useState function.
- Import
useState
as the first step:
import React, {useState} from ‘react’;
- Create the component function:
Let’s name the component BlogPost:
import React, { useState } from 'react';
function BlogPost() {
return (
<div>
</div>
);
}
export default BlogPost;
This is the basic component without any content in it. Before we create the content let’s understand each part of the snippet:
We have declared a Functional Component that is a JavaScript function.
Return statement for the function that defines the content to be rendered.
Note that JSX requires wrapping everything in a single parent element (in this case, a <div>).
Export statement at the end of the code to make the BlogPost component accessible in other components of the application.
- Declaring the useState for the likes of the BlogPost:
import React, { useState } from 'react';
function BlogPost() {
const [likes, setLikes] = useState(0);
return (
<div>
</div>
);
}
export default BlogPost;
So, what we did here is initialize the likes state to 0 using useState
.The likes
state variable will keep track of the number of likes for the blog post. Also, creating a setLikes function to track and update the number of likes.
- Adding Interactivity with Event Listeners:
Now that we have our initial setup using useState
to keep track of likes, let's make our blog post interactive. To do this, we'll use event listeners and a button that allows users to "like" the post.
First, let's add a button to our BlogPost
component. This button will be used as the control to update the number of likes when clicked.
import React, { useState } from 'react';
function BlogPost() {
const [likes, setLikes] = useState(0);
return (
<div>
<p>This is an amazing blog post!</p>
<p>Likes: {likes}</p>
<button>Like</button> {/* This is our Like button */}
</div>
);
}
export default BlogPost;
Adding an Event Listener
To make the button interactive, we need to add an event listener to it. An event listener "listens" for a specific event, such as a click, and performs an action when that event occurs.
In this case, we want to listen for a click on the "Like" button and increment the likes
state when it's clicked. We get this by adding an onClick
event listener to the button.
<button onClick={() => setLikes(likes + 1)}>Like</button>
Here's a breakdown of what's happening in this line:
onClick
: This is the event we're listening for – a click on the button.() => setLikes(likes + 1)
: This is the function that will run when the button is clicked. It updates thelikes
state by incrementing it by 1.
Result: Adding Interactivity
With the event listener, our BlogPost
component now becomes interactive. When users click the "Like" button, the likes
state is updated, and the number of likes displayed on the page increases.
// BlogPost Component: This component displays a blog post and allows users to like it.
import React, { useState } from 'react';
function BlogPost() {
// State for tracking the number of likes
const [likes, setLikes] = useState(0);
return (
<div>
{/* Blog post content */}
<p>This is an amazing blog post!</p>
<p>Likes: {likes}</p>
{/* Like button with click event */}
<button onClick={() => setLikes(likes + 1)}>Like</button>
</div>
);
}
export default BlogPost;
That’s it. the final code will look like this ☝️ With this simple setup, our blog post component is completed as we wanted it to be.
I have added some tailwindcss to make the component look appealing
this is how it turns,
Practical Uses of useState
Here is a list of example use cases where we can use useState
Form Handling: For capturing and managing user input in forms, such as registration forms, and login forms.
Counting Stuff: For keeping track of numbers, like how many people liked a post or items in a shopping cart.
Progress Bars: To show how far along users are in a process, like signing up.
News Updates: Showing the latest news without reloading the whole page.
Surveys and Quizzes: Keeping track of answers and scores.
Show/Hide Content: To make things appear or disappear when users click buttons, like showing or hiding a menu. 👀👇
(To make something appear or disappear when a button is clicked, you can useuseState
to control whether it's visible or not by changing a variable, and then you update what's shown on the page based on that variable.)
And whatnot! there are so many cases where you can use this hook and make complete use of it by managing data, adding interactivity, and simplify your code.
👋