This document explains the concept of state in React class components, how it differs from props, and how state enables dynamic, interactive user interfaces.
This document explores state in React class components, including local and shared state, how state enables dynamic UI updates, and the differences between state and props. It provides practical examples and a comparison table for clear understanding.
State in React is a plain JavaScript object used to represent information about a component’s current situation. State allows components to create dynamic and interactive user interfaces by tracking and responding to changes in data.
this.setState, which triggers a re-render of the component. 1class Counter extends React.Component {
2 constructor(props) {
3 super(props)
4 this.state = { count: 0 }
5 }
6
7 increment = () => {
8 this.setState({ count: this.state.count + 1 })
9 }
10
11 render() {
12 return (
13 <div>
14 <p>Count: {this.state.count}</p>
15 <button onClick={this.increment}>Increment</button>
16 </div>
17 )
18 }
19}
Props and state are both used to manage data in React, but they serve different purposes:
| Feature | State | Props |
|---|---|---|
| Mutability | Mutable (can be changed by the component) | Immutable (read-only in child) |
| Scope | Local to the component | Passed from parent to child |
| Usage | Manages internal data and UI updates | Passes data and methods to children |
| Modification | Updated with setState | Cannot be modified by the child |
1class TestComponent extends React.Component {
2 constructor(props) {
3 super(props);
4 this.state = { id: 1, name: props.name, age: 25 };
5 }
6
7 render() {
8 return (
9 <div>
10 <p>Name: {this.state.name}</p>
11 <p>Age: {this.state.age}</p>
12 </div>
13 );
14 }
15}
16
17// Usage
18<TestComponent name="John" />
19<TestComponent name="Jill" />
State is fundamental to building interactive React components. It allows components to manage their own data, respond to user actions, and update the UI dynamically. Understanding the distinction between state and props is essential for effective React development.
(1) State allows components to manage and track dynamic data that can change over time, enabling interactive UIs.
(3) Props cannot be modified by the child component; they are read-only.
| Concept | Description |
|---|---|
| A. State | 1. Passes data from parent to child |
| B. Props | 2. Manages internal data and UI updates |
| C. setState | 3. Updates the component’s state and triggers a re-render |
A-2, B-1, C-3.
State changes in a React component always trigger a re-render of that component.
True. Updating state with setState causes the component to re-render and update the UI.