Understanding useState in React in 5 Minutes
When building web applications with React, we often rely on hooks to add functionality to functional components. Hooks allow us to use features typically reserved for class components — like managing state and lifecycle methods — without the need for classes or the this keyword. One of the most popular hooks in React is useState , lets explore it !!
What is useState?
The useState hook lets you add state to functional components. Whether you're working with numbers, strings, arrays, or objects, useState helps you manage updates to your data and re-render your component whenever the data changes. For example, you might use useState to keep track of a counter that increments each time a button is pressed.
useState Syntax
The syntax for useState is straightforward:
const [variableName, setVariableName] = useState(initialValue);
variableName is the state variable that holds the current value.
setVariableName is a function that updates the state.
initialValue is the initial value you want the variable to hold.
Example: Using useState for a Counter
Let’s look at a simple example where we create a counter that increments by one each time a button is pressed.
import React, { useState } from 'react';
function counter ()
{
const [count, setCount] =useState(0);
function increaseCount()
{
setCount(count+1);
}
return (
<div>
<p>{count}</p>
<button onclick={increaseCount}>Tap</button>
</div>
)
}
export default counter;
In this code:
count is the state variable with an initial value of 0.
setCount is a function that lets us update count.
Each time we call increaseCount, setCount is used to update count by incrementing it by 1.
A Few Tips
Rerendering on State Change: Every time you call setCount with a new value, React rerenders the component to display the updated state.
Avoid Direct State Modification: Always use the setter function (setCount here) instead of modifying the variable directly. This ensures React knows about the update.Initial Value: You can pass any initial value to useState, whether it’s a string, array, or object.
Using useState is a simple yet powerful way to manage local state in React, and it’s often the first hook developers learn. Mastering it is essential for creating dynamic, interactive applications.
Top comments (0)