React useState Hook
The useState hook is one of the most commonly used hooks in React. It allows functional components to manage state, which was previously only possible in class components. With useState, you can create state variables and update them, causing the component to re-render whenever the state changes.
1 Basic Counter Example
In this example, we will create a simple counter component. The useState hook will be used to manage a state variable count that stores the current count value. A button click will increment the count by 1.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // Initialize state with 0
const increment = () => {
setCount(count + 1); // Update state to increment count
};
return (
<div>
<h2>Count: {count}</h2>
<button onClick={increment}>Increment</button>
</div>
);
}
export default Counter;
Explanation:
useState(0): Initializes the state variablecountwith a value of0.setCount: Updates the state when the button is clicked.- The component re-renders whenever the state changes, displaying the updated count.
Output:
2 Example: Managing Form Input using useState Hook
This example demonstrates how to use the useState hook to manage form input values. The state variable name will hold the value entered in the input field, and we will update it dynamically as the user types.
import React, { useState } from 'react';
function NameForm() {
const [name, setName] = useState(''); // Initialize state with an empty string
const handleChange = (event) => {
setName(event.target.value); // Update state with input value
};
return (
<div>
<input type="text" value={name} onChange={handleChange} placeholder="Enter your name" />
<p>Hello, {name}!</p>
</div>
);
}
export default NameForm;
Explanation:
useState(''): Initializes the state variablenamewith an empty string.handleChange: Updates thenamestate as the user types in the input field.- The value of the input field is controlled by the state, making it a controlled component.
Output:
3 Example: Toggle Visibility using useState Hook
In this example, we will create a component that toggles the visibility of a message using the useState hook. The state variable isVisible determines whether the message is shown or hidden.
import React, { useState } from 'react';
function ToggleMessage() {
const [isVisible, setIsVisible] = useState(false); // Initialize state with false
const toggleVisibility = () => {
setIsVisible(!isVisible); // Toggle the visibility state
};
return (
<div>
<button onClick={toggleVisibility}>{isVisible ? 'Hide' : 'Show'} Message</button>
{isVisible && <p>Hello, World!</p>}
</div>
);
}
export default ToggleMessage;
Explanation:
useState(false): Initializes the state variableisVisiblewithfalse.setIsVisible: Toggles the value ofisVisiblebetweentrueandfalse.- The message is conditionally rendered using
&&, which shows the message only whenisVisibleistrue.
Output:
4 Example: Multiple Counters using Multiple useState Hooks
In this example, we will use multiple useState hooks to manage different state variables. This is useful when a component needs to track multiple independent pieces of data.
import React, { useState } from 'react';
function MultiCounter() {
const [countA, setCountA] = useState(0); // State for counter A
const [countB, setCountB] = useState(0); // State for counter B
return (
<div>
<h2>Counter A: {countA}</h2>
<button onClick={() => setCountA(countA + 1)}>Increment A</button>
<h2>Counter B: {countB}</h2>
<button onClick={() => setCountB(countB + 1)}>Increment B</button>
</div>
);
}
export default MultiCounter;
Explanation:
useState: Used twice to create independent state variablescountAandcountB.setCountAandsetCountB: Update the respective counters.- This demonstrates how multiple pieces of state can coexist within the same component.
Output:
Conclusion
The useState hook is a powerful tool that simplifies state management in functional components. Whether you’re handling user input, toggling visibility, or tracking multiple state variables, useState makes it easy to build dynamic and interactive React applications.
