React.js State Management
What is State Management in React.js?
State management is crucial in React for handling dynamic data and user interactions.
Understanding Component State
State represents the data that can change over time within a component.
Each component can maintain its own state, which determines how it renders and behaves.
Setting Initial State
Inline with the course content, you define state in the constructor as an instance of this.state when the class component is initialized.
Example:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
</div>
);
}
}
In ‘states functional components’ you can initialize the state with the useState hook.
Example:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
</div>
);
}
Updating State using setState()
To update state in React, you should never modify this.state directly.
Instead, use the setState() method provided by React.
Example:
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()}>Increment</button>
</div>
);
}
}
In functional components, you can use the updater function returned by useState to update state.
Example:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function incrementCount() {
setCount(prevCount => prevCount + 1);
}
return (
<div>
<p>Count: {count}</p>
<button onClick={incrementCount}>Increment</button>
</div>
);
}
Conditional Rendering based on State
You can show or hide components or elements by putting ECMAScript expressions in JSX, which define the state of your component.
Example:
The initially transparent paragraph will only be displayed when isToggleOn value is true here.
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {
isToggleOn: true
};
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<div>
<button onClick={() => this.handleClick()}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
{this.state.isToggleOn && <p>The button is ON</p>}
</div>
);
}
}