Understanding React State
Setting State
• In React, state is an object that stores the dynamic data of a
component and determines how that component renders and
behaves.
• React's useState hook (for functional components) or this.state
and this.setState (for class components) is used to manage state.
1. State in Functional Components (using useState)
• The useState hook is used to declare and update state in functional components.
• Syntax:
import React, { useState } from 'react’;
function ComponentName() {
// Declare state variable and its updater function
const [stateVariable, setStateVariable] = useState(initialValue);
// Example of setting state
const updateState = () => {
setStateVariable(newValue);
};
return (
<div>
<p>{stateVariable}</p>
<button onClick={updateState}>Update State</button>
</div>
);}
export default ComponentName;
Example:
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(count - 1)}>Decrement</button>
</div> );}
• 2. State in Class Components (using this.state and this.setState)
• In class components, state is defined as an object, and it can be updated using
this.setState.
• Syntax:
import React, { Component } from 'react’;
class ComponentName extends Component {
constructor(props) {
super(props);
// Initialize state
this.state = {
stateVariable: initial Value,
}; }
// Example of setting state
updateState = () => {
this.setState({ stateVariable: newValue });
};
Example:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0, };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
decrement = () => {
this.setState({ count: this.state.count - 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
<button onClick={this.decrement}>Decrement</button>
</div> ); }}
render() {
return (
<div>
<p>{this.state.stateVariable}</p>
<button onClick={this.updateState}>Update
State</button>
</div> ); }
}
export default ComponentName;