The Updater Function
What if a handler calls the setter several times? A super like should add 3 likes:
function handleSuperLike() {
setLikes(likes + 1);
setLikes(likes + 1);
setLikes(likes + 1);
}But it adds only 1. You know why from the last exercise: likes doesn't change during the handler. With likes at 0, the handler says "the new value is 1" three times, and React renders with 1.
When the new value is computed from the old one, give the setter a function instead of a value:
function handleSuperLike() {
setLikes((likes) => likes + 1);
setLikes((likes) => likes + 1);
setLikes((likes) => likes + 1);
}Such a function is called an updater function. React puts it in a queue, and in the next render, it calls the functions in the queue in order, giving each one the value that the one before it returned: 0 becomes 1, 1 becomes 2, and 2 becomes 3. The page shows ♥ 3.
The parameter has the same name as the state here, but inside the arrow function, likes is the parameter: the latest value, not the one from the snapshot. You can name it differently, (previous) => previous + 1 works just the same.
When do you need it? A fixed value, like setLikes(0), doesn't depend on the old one, so give the value. When the new value is made from the old one, setLikes(likes + 1) often works too, but only as long as nothing else in the same handler changes that state. The updater function always works, and it keeps working when the handler grows. So from now on, this course uses it whenever the new value is computed from the old one.
Instructions
Super like adds only 1. Change handleLike() so that it gives setLikes() an updater function. Then Super like adds 3, and Like still adds 1.
Add a button Mega like that adds 10: its handler calls handleLike() ten times in a for loop.