How parameter is working in single line expression of arrow function in useState function

Viewed 169
 const tick = () => {
     setCount(prevCount => prevCount+1);
        
       // setCount(count+1);
    }

My question is from where prevCount variable is getting it's initial value? How the expression supplied to setCount() is working?

I have created a react example to explain.

React js example, please refer tick function in interval.jsx component.

Update: As per a comment by Dennis Vash on my question I am supplying callback function to setCount() then Why it does not work if I write it like this?

   const tick = () => {
           setCount(updateCount(count))
            
           // setCount(count+1);
        }

     const updateCount = (myCount) => {
        return myCount + 1;
    }
2 Answers

the Arrow function works like this,

For single parameter brackets optional,
prevCount => prevCount+1 -> function(prevCount){return prevCount+1}
(prevCount) => prevCount+1 -> function(prevCount){return prevCount+1}

And for multiple parameters You need to add braket,
(prevCount, a, b, c) => prevCount+1 -> function(prevCount, a, b, c){return prevCount+1}

And for empty parameter You need to add empty brackets,
() => prevCount+1 -> function(prevCount){return prevCount+1}

For more info read, MDN's doc


## UPDATE:

here in your updated question, updateCount(count) is getting called directly. So use something like this,

setCount(updateCount)

You are getting setCount function from useState hook. which is itself a React inbuilt function.

So setCount is a function that accepts a function as a call back function. Your code

setCount(prevCount => prevCount+1);

Let's simplify it for you

setCount(function(prevCount) {
    return prevCount+1
})

So here you can see that setCount accepts a function which will be called back as the last step of execution of the setCount function, at that time setCount will pass a previous value of the state variable as an argument to the callback function.

Related