reactjs update state code example
Example 1: react how to update state array
const initialState = [
{ name: "foo", counter: 0 },
{ name: "far", counter: 0 },
{ name: "faz", counter: 0 }
];
const [state, setState] = useState(initialState);
const clickButton = () => {
let temp_state = [...state];
let temp_element = { ...temp_state[0] };
temp_element.counter = temp_element.counter+1;
temp_state[0] = temp_element;
setState( temp_state );
}
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: reactjs update state example
{
hasBeenClicked: false,
currentTheme: 'blue',
}
Example 4: reactjs update state example
{
hasBeenClicked: false,
currentTheme: 'bluesss',
}s