Managing State with useState()
Explore how to manage state using the useState Hook in React function components. Understand how to replace class component state management with hooks, use array destructuring for state and setter access, and handle multiple independent states effectively.
We'll cover the following...
We'll cover the following...
Changing state in a function component
Let’s have a look at how the state is accessed and modified using the class component:
import React from 'react';
import ReactDOM from 'react-dom';
class Counter extends React.Component {
state = {
value: 0,
};
render() {
return (
<div>
<p>Counter: {this.state.value}</p>
<button
onClick={() => this.setState((state) => ({ value: state.value + 1 }))}
>
+1
</button>
</div>
);
}
}
ReactDOM.render(<Counter />, document.getElementById('root'));
Here, we have implemented a simple counter that keeps track of how many times we press the “+1 ...