dev Await
February 2025
React useState: A Simple Guide
What is useState? 🤔
useState is a React Hook that allows functional components to manage and update state. Think of state as a component's memory - it stores data that can change over time.
Why use useState? 🎯
To store changing data in components
To update UI based on user interactions
To manage form inputs
To trigger re-renders when data changes
When to use useState? ⏰
Use useState when you need to:
Track values that change (like form inputs)
Toggle between states (show/hide elements)
Store user interactions (like button clicks)
Manage loading states
Where to use useState? 📍
Only inside React functional components
At the top level of your component (not inside loops or conditions)
Simple Example 💻
import React, { useState } from 'react';
function NameGreeter() {
// Initialize state with empty string
const [name, setName] = useState('');
// Handle input change
const handleChange = (event) => {
setName(event.target.value);
};
return (
<div>
<input
type="text"
value={name}
onChange={handleChange}
placeholder="Enter your name"
/>
{name && <p>Hello, {name}!</p>}
</div>
);
}
How useState Works 🛠️
Declaration:
const [state, setState] = useState(initialValue);
state: current state value
setState: function to update state
initialValue: starting value of state
Updating State:
setState(newValue); // Direct update setState(prev => prev + 1); // Update based on previous state
Types of State:
const [text, setText] = useState(''); // String const [count, setCount] = useState(0); // Number const [isActive, setIsActive] = useState(false); // Boolean const [user, setUser] = useState({ // Object name: '', age: 0 });
Common Mistakes to Avoid ⚠️
Don't call useState inside loops or conditions
Don't modify state directly; always use setState
Don't forget that state updates are asynchronous
Quick Tips 💡
Use separate state variables for unrelated data
Use a single state object for related data
Always use the setter function to update state
Remember state updates trigger re-renders
Use the functional update form when new state depends on old state
That's all you need to know to get started with useState! Happy coding! 🚀