on state update react code example
Example 1: state with react functions
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
You clicked {count} times
);
}
Example 2: update state in react
You have to use setState() for updating state in React
{
hasBeenClicked: false,
currentTheme: 'blue',
}
setState({
hasBeenClicked: true
});
Example 3: react setState
incrementCount() {
// Note: this will *not* work as intended.
this.setState({count: this.state.count + 1});
}
handleSomething() {
// Let's say `this.state.count` starts at 0.
this.incrementCount();
this.incrementCount();
this.incrementCount();
// When React re-renders the component, `this.state.count` will be 1, but you expected 3.
// This is because `incrementCount()` function above reads from `this.state.count`,
// but React doesn't update `this.state.count` until the component is re-rendered.
// So `incrementCount()` ends up reading `this.state.count` as 0 every time, and sets it to 1.
// The fix is described below!
}
Example 4: reactjs update state example
{
hasBeenClicked: false,
currentTheme: 'blue',
}
Example 5: reactjs update state example
{
hasBeenClicked: false,
currentTheme: 'bluesss',
}s