top of page
Logo der Online Agentur mdwp

State

In React JS, the term 'State' refers to a built-in object that allows you to store property values that belong to a component. This state in a React component is mutable, meaning it can be changed, but it should not be access directly – you will use setState() method to modify it.

State is often used to store property values that need to be displayed in render() and that can change over time or in response to user action. It's particularly useful because when the state object changes, the component re-renders.

For example, say we built a simple counter application in React. The count value changes with user's action, hence it should be kept in state.

```jsx
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}

incrementCount = () => {
this.setState({
count: this.state.count + 1
});
}

render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.incrementCount}>Increase</button>
</div>
);
}
}
```

In the example above, the state of the 'Counter' component is initially declared in the constructor and starts as `{ count: 0 }`. When the button is clicked, it runs the 'incrementCount' function, which uses `this.setState` to change the 'count' value in the state. The display is automatically updated thanks to React's re-rendering when state changes.

bottom of page