简体   繁体   中英

When to use callback useState

It's maybe simple question, but the i'm not fully understand useState

I have confuse with when to use callback with useState, say example, i have an hook

const[count,setCount] = useState(0)

We can easy to update, for example, if i want to update the number, i can do:

setCount(count+1)

But if we have some code like setInterval,we want to increase the count every 1 second, when do the same as above

setTimeout(()=>{
 setCount(count+1)
},1000)
console.log(count)

It will not increase even 1s passed

But we do

 setTimeout(()=>{
     setCount((count)=>{count+1}
    },1000)
    console.log(count)

But why it work???

My question is

When to use callback in useState?

You use the callback when you want to keep the previous state and add something to it.

For example, let's say we have a counter in your case

const [counter, setCounter] = useState(0);

If I want this value to increase every second or when I press a button, I would use the following:

setCounter(prev => (prev + 1);
// Or
setCounter(counter => (counter + 1);

prev will be the same value as counter doesn't matter what you call it.

And since you will be using setInterval you will have to do this operation in a useEffect hook is the reason you will need the callback otherwise if you keep setting the value to counter + 1 without using the callback you will just be 0 + 1 all the time.

Unless you wanna use it for something like increasing a like button counts. In that case you don't need callbacks.

Try reading and understanding those articles and docs:

In React, when you update a state property, with respect to its previous value, you should use,

setState((state,props)=>{ return doSomethingWith(state.property)})

In your code (using hooks): setCount((count)=>(count+1))

This is due to the fact that, state updates may be asynchronous in React .

By the way setCount((count)=>(count+1)) is not the same as setCount((count)=>{count+1}) . In the 2nd case, the curly braces form an empty statement, & hence count+1 is not returned. In lambda functions the auto-return happens only in the case of a single expression .

Whenever a current state value update depends on the previous state, we can use a callback function.

if we have some code like setInterval,we want to increase the count every 1 second

For setInterval , Each second we need to update the count based on the previous state.This will update the count every 1 second interval.

setInterval(() => { setCount((count) => count + 1); }, 1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM