Understanding React State
What is State in React?
In React, state refers to an internal data object used by components to remember information between renders.
Why Use State?
- To make components interactive.
- To store and manage changing data (e.g., user input, API responses).
- To trigger re-rendering when data changes.
How State Works?
- State is initialized using the
useState hook.
- Calling the setter function (e.g.,
setCount) updates the state.
- React re-renders the component with the new state value.
Multiple State Variables
const [name, setName] = useState('John');
const [age, setAge] = useState(25);
State vs Props
- State: Local to the component. Mutable via
useState.
- Props: Received from parent component. Immutable.
When to Use State?
- Form inputs
- Counters
- Toggle UI elements (show/hide)
- Storing fetched API data
Rules of State
- State should not be modified directly (always use the setter function).
- State updates may be asynchronous.
- State is unique per component instance.
Complex State (Objects & Arrays)
const [user, setUser] = useState({ name: 'John', age: 25 });
// Update name only
setUser(prev => ({ ...prev, name: 'Jane' }));
Important Notes
- Using state improperly can cause unnecessary re-renders.
- Use derived state carefully to avoid inconsistencies.
Conclusion
State is the heart of React components, making them interactive and dynamic. It stores data that changes over time and causes the component to re-render, ensuring the UI reflects the latest values.