Reputation: 3
import React, { useState } from 'react';
import './App.css';
const app1 = () => {
let [count, setCount] = useState(10);
let initialValue = count;
const increase = () => {
setCount(count += 1);
setCount(count += 1);
}
const decrease = () => {
setCount(count -= 1);
setCount(count -= 1);
}
const resetCounter = () => {
setCount(initialValue);
console.log(initialValue);
}
return (
<div className="App">
<button onClick={increase}>+</button> {count} <button onClick={decrease}>-</button>
<div><button onClick={resetCounter}>Reset</button></div>
</div>
);
}
export default app1;
The Reset Button is not behaving properly. When I click on the Reset Button the initial value 10 is not printed. Instead it prints the current value. Can someone explain and correct the code please?
Upvotes: 0
Views: 73
Reputation: 31
You have to replace each call to setCount(newValue)
with setCount((oldvalue)=> newValue)
.
This is because you are relying on the old value in order to calculate the new one.
You can learn more here Functional updates
Upvotes: 0
Reputation: 111
import React, { useState } from 'react';
import './App.css';
const initialValue = 10;
const app1 = () => {
let [count, setCount] = useState(initialValue);
const increase = () => {
setCount(count += 1);
setCount(count += 1);
}
const decrease = () => {
setCount(count -= 1);
setCount(count -= 1);
}
const resetCounter = () => {
setCount(initialValue);
console.log(initialValue);
}
return (
<div className="App">
<button onClick={increase}>+</button> {count} <button onClick={decrease}>-</button>
<div><button onClick={resetCounter}>Reset</button></div>
</div>
);
}
export default app1;
The issue happens because react renders when you use setCount and updates the initial value everytime.
Upvotes: 0
Reputation: 421
the initialValue is always the count, which means that it's not 10 it's the current count. you should extract the initial value outside to a const, i.e:
const INITIAL_VALUE = 10;
const app1 = () => {
let [count, setCount] = useState(INITIAL_VALUE);
...
const resetCounter = () => {
setCount(INITIAL_VALUE);
}
}
Upvotes: 3