score:0

class Hello extends React.Component {
    state = { counter: 0 };

    increment = () => {
        const { counter } = this.state;

        this.setState({ counter: counter + 1 });
    };

    decrement = () => {
        const { counter } = this.state;

        this.setState({ counter: counter - 1 });
    };

    render() {
        const { counter } = this.state;

        return (
            <div>
                <h1>{counter}</h1>

                <p>
                    <button onClick={this.increment}>Increment</button>
                </p>
                <p>
                    <button onClick={this.decrement}>Decrement</button>
                </p>
            </div>
        );
    }
}

ReactDOM.render(<Hello />, document.getElementById("container"));

I hope this helps you pick react up! let me know if you have any questions :)

score:1

Because you aren't intercepting the change in state, it is causing a re-render, which in turn is causing your incremented instance property to be used. This is by design. Any changes to React state will cause the component to re-render, unless you are using a lifecycle hook to control whether or not that should happen.

See https://reactjs.org/docs/react-component.html#shouldcomponentupdate

score:1

React use this.state and setState because it has some own purpose.

By using React state mechanism, we got benefit like the verbosity, functional-like programming style which function should be pure and not mutate the data.

Every time you call setState it will use the new value instead mutate the existing and make the behavior unpredictable.

Also you could benefit to prevent component re-render or update by utilize shouldComponentUpdate which check props/state inside it.

After your apps is getting complicated, then library like Redux could save your ass in the future. For simpler component or apps, React state is enough.

Further reading:

https://reactjs.org/docs/faq-state.html

https://reactjs.org/docs/state-and-lifecycle.html

https://reactjs.org/docs/react-component.html#shouldcomponentupdate

https://spin.atomicobject.com/2017/06/07/react-state-vs-redux-state/

score:1

You can replace setState on forcrUpdate. If your team use decorative style of code, then never use setState({}) or forceUpdate(). React's authors recommendes make components like pure functions.


Related Query

More Query from same tag