I am quite new to react and have problems in understanding the useState Hook - or more specifically the aspect of the previousState.
A normal useState Hook, and probably most common example, looks like this:
import React, { useState} from 'react';
export default function CounterHooks({ initialCount }){
const [count, setCount] = useState(initialCount);
return (
<div>
<button onClick={() => setCount(count -1)}>-</button>
<span>{count}</span>
<button onClick={() => setCount(count + 1)}>+</button>
</div>
)
}
What I am understanding so far, is the following:
- I call the useState() function/Hook? and pass in the argument of the initial State (initialCount)
- I get back an array which i immediately destruct into the variables count and setCount (which is function)
- With setCount() i can update the state and therefore the count variable
So far so good, i think... ;)
Sometimes I see the same counter example with prevState (prevCount) which i do not understand:
<button onClick={() => setCount(prevCount => prevCount -1)}>-</button>
What happens here? This part i do not understand. My thoughts so far:
- In this case, I somehow access the previous count value.
- setCount expects now a function
- setCount is now run asynchron
- Where is this function coming from?
- Where is prevCount coming from?
- When i run this, what is put into prevCount?
Do you understand my confusion? I am not sure how i should frame this differently...
Thank you very much for your help.
previousState
as a parameter to that function. This is how you can change the state based on the previous state. Please find a more detailed answer here: #56405319 – HorsasetState
makes it clearer (towards the end): reactjs.org/docs/react-component.html#setstate . If the new state does not depend on the previous state then there is no need to pass a function. – Trainband