Managing State with useState()
Learn how to define, manage, and update states in function components using Hooks.
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” button. While it is not the most creative example, it demonstrates how we can use Hooks to simplify code. In this example, we read the current value with this.state.value
and increment the counter by a button that is placed below. Once the button is clicked, this.setState()
is called, and we set the new value to the previous value
, which we increment by 1
.
But let’s have a look at how the same functionality can be implemented using the useState()
Hook in a function component:
Get hands-on with 1200+ tech skills courses.