In React, state is managed differently in functional components and class-based components. Here's a precise explanation for both:
1. Managing State in Functional Components
Use the useState hook to manage state.
import React, { useState } from 'react';
function MyComponent() {
// Declare state variable and setter function
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default MyComponent;
2. Managing State in Class-Based Components
Use the this.state object and this.setState method.
import React from 'react';
class MyComponent extends React.Component {
// Initialize state in the constructor
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
// Method to update state
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
export default MyComponent;