...

/

Managing State with useState()

Managing State with useState()

Learn how to define, manage, and update states in function components using Hooks.

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 ...