VITSOLS
2025-11-06
🔹 What is State in React?
State represents dynamic data in a component. It helps React components to track user inputs, API responses, or UI interactions such as toggles, counters, and form values.
// Example: Using State in a Class Component import React, { Component } from "react"; class Counter extends Component { constructor() { super(); this.state = { count: 0 }; } increment = () => { this.setState({ count: this.state.count + 1 }); }; render() { return ( <div> <h2>Count: {this.state.count}</h2> <button onClick={this.increment}>Increment</button> </div> ); } } export default Counter;
🔹 Using State in Functional Components (useState Hook)
React’s useState() hook allows functional components to manage state easily.
// Example: Using useState Hook import React, { useState } from "react"; function Counter() { const [count, setCount] = useState(0); return ( <div> <h2>Count: {count}</h2> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); } export default Counter;
🔹 What is setState()?
The setState() method is used to update the component’s state. It triggers a re-render so the UI reflects the latest data. In functional components, setCount() from useState() works similarly.
// Example: Updating State Using setState()
this.setState({ key: value });
💡 Real-Time Use Cases of State
- Form Handling: Capture and manage user inputs dynamically.
- Toggle Menus or Modals: Open and close UI elements interactively.
- APIs and Dynamic Data: Store and display data fetched from APIs.
- Theme Switching: Manage dark/light mode states for better UX.
🚀 Why Use State in React?
State provides the backbone for building dynamic and interactive user interfaces. It ensures your UI always reflects the current data, giving users a responsive and seamless experience.
🧠 In Summary
Understanding state and setState() is essential to building interactive React applications. Whether you use class-based or functional components, proper state management keeps your app’s data flow predictable, consistent, and efficient.