Home > OS >  When to use callback useState
When to use callback useState

Time:02-02

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?

CodePudding user response:

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.

CodePudding user response:

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);

CodePudding user response:

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:

  •  Tags:  
  • Related