arrow_back
Back

React state: useState, updates, and lifting state up

Andrew Dorokhov Andrew Dorokhov schedule 1 min read
menu_book Table of Contents

To create a state object we need to set a state property. We can change this property anytime unlike the props one.

class Header extends React.Component {
    
    constructor(props) {
        super(props);
        this.state = {
            number: 1234
        };
    }
    
    render() {
        return <h2>{this.state.number}</h2>;
    }
};

How to change states?

We shouldn’t change the state object directly. We should use the setState() method instead.

When we don’t depend on the previous state (text typing, for example):

this.setState({
    number: 1235
});

When the previous state is important we use callback function, so it will be called after all previous states are updated.

this.setState(state => ({
    number: 1235
}));

We don’t need to pass to the setState() an object with all the properties. It can be even one property. This property will be overwritten and the rest will be left the same.

What will happen?

Usually after calling the setState() method the render() method will be triggered.

Controlled and uncontrolled inputs

open_in_new https://goshacmd.com/controlled-vs-uncontrolled-inputs-react/

code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward