State in React
State in React
50
In React, state refers to the current data that a component is holding, which can be used to control the appearance of the UI and response to user interaction over time. A component can set and update its own state using the setState()
method, which triggers a re-render to reflect the changes in the UI.
State is often used to implement dynamic behavior in React components.
For example, a simple counter component might use state to keep track of the current count:
class Counter extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } increment() { this.setState({ count: this.state.count + 1 }); } render() { return ( <div> <p>Count: {this.state.count}</p> <button onClick={() => this.increment()}>Increment</button> </div> ); } }
In the above example, the constructor()
method initializes the component's state with a count
property set to 0. The increment()
method updates the state by calling setState()
with a new object that contains the updated count
value. Finally, the render()
method displays the current count value and a button that triggers the increment()
method.
By using state, the counter component can update and display its current count over time based on user interaction. Understanding state is a fundamental part of building dynamic and interactive applications with React.
March 25, 2023