Web II React States Lesson005
Web II React States Lesson005
React state is a mechanism for components to manage and update their own data,
triggering UI re-renders when changes occur. It is essential for creating dynamic
and interactive user interfaces.
State is A component's internal memory.
It holds data that can change (e.g., user input, API responses, UI toggle status).
When state changes, React automatically re-renders the component to reflect
updates.
Key Concepts:
State Variables: Use the useState hook to declare state variables within
functional components. It returns an array with two elements: the current
state value and a function to update it.
const [count, setCount] = useState(0);
Updating State: Always update state using the provided setter function
(setCount in the example above). Directly modifying the state variable will
not trigger a re-render. For complex state updates based on the previous
state, use a functional update.
setCount(prevCount => prevCount + 1);
State Immutability: When dealing with objects or arrays in state, avoid
direct mutation. Instead, create a new copy of the object or array with the
desired changes and update the state with the new copy.
const [user, setUser] = useState({ name: 'John', age: 30 });
setUser({ ...user, age: 31 }); // Correct way
Using State with useState Hook
To make React track changes, we use the useState hook.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div className="counter">
<p>Current count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}
export default Counter;
How it works:
1. useState(0) → Creates a state variable count (initial value 0).
2. setCount → A function to update count.
3. When setCount is called, React re-renders the component with the new
value.
Key Rules of State
Rule 1: Never Modify State Directly