Trying to learn React Hooks and new to coding in general and I noticed prevCount is not declared beforehand. What is the value of prevCount and how come you do not have to declare it beforehand like const prevCount? I do not understand where this came from, is it just a variable you declare in setCount or useState that accesses the default value (in this case, initialCount) of count?
const [count, setCount] = useState(initialCount);
return (
<>
Count: {count}
<button onClick={() => setCount(initialCount)}>Reset</button>
<button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
<button onClick={() => setCount(prevCount => prevCount 1)}> </button>
</>
);
}
Reference: https://reactjs.org/docs/hooks-reference.html
CodePudding user response:
prevCount refers the value of count
at the time of evaluation. In practice, lets take a look a modification of your example:
function TestCompononent() {
const initialCount = 0;
const [count, setCount] = useState(initialCount);
function handleChange1() {
setCount(count 1)
}
function handleChange2() {
setCount(prevCount => prevCount 1)
}
function handleChange3() {
setCount(count 1)
setCount(count 1)
}
function handleChange4() {
setCount(prevCount => prevCount 1)
setCount(prevCount => prevCount 1)
}
return (
<>
Count: {count}
<button onClick={() => setCount(initialCount)}>Reset</button>
<button onClick={handleChange1}>handleChange1</button>
<button onClick={handleChange2}>handleChange2</button>
<button onClick={handleChange3}>handleChange3</button>
<button onClick={handleChange4}>handleChange4</button>
</>
);
}
Ok, so now in this example, handleChange1
and handleChange2
will behave identically, BUT handleChange3
and handleChange4
are not.
Let's imagine when we call handleChange3
that we haven't done anything else, so count
is equal to 0
.
When we call handleChange3
we are doing
setCout(count 1) // count === 0
setCout(count 1) // count === 0
which means that at the next render cycle, count will equal 1
In the same scenario, if we called handleChange4
instead, we would be doing
setCout((prevCount) => prevCount 1) // prevCount === 0
setCout((prevCoutn) => prevCount 1) // prevCount === 1
which means that at the next render cycle, count will equal 2
Hope that helps illustrate what's going on :)
CodePudding user response:
Official docs contains bit of information as you have pasted the link in there
The function will receive the previous value, and return an updated value
prevCount
- is a functional
scope variable
, updated with the callback function. You don't define these variables as they exist and die within the function and have no meaning out of it. I
The click will update the state using the previous state using a callback. prevCount
is is the most recent value of count.
CodePudding user response:
the prevCount it is the current value of your state before set new value to your state so if state was 1 and click on button that sum 1 to old value that mean old=>old 1 equal 1=>1 1 that will return 2