Professional Documents
Culture Documents
-> It returns the pair representing the current state and a function that lets you update
the current state.
-> It receives the initial state value as an argument, it doesn’t necessarily have an
object, it could be number, string, depending on what is needed.
-> To update multiple values, it’s ok to call useState multiple times.
-> updating a state variable with useState always replaces the previous state, this is
the key difference when compare to setState that merges state.
-> it returns the same state value passed as an argument when the initial render
happens.
->
setTheArray(oldArray=>[...oldArray, newElement])
Examples
const [theArray, setTheArray] = useState(initialArray)
const [theObject, setTheObject] = useState(initialObject)
-> useEffect(()=> {
async function getLastData(){
await getLast();
}
})
-> useState is asynchronous , the main issue here is not just the asynchronous nature
but the fact that state values are used by functions based on their current closures, and
state update will reflect in next re-render by which the existing closures are not
affected, but new ones are created.
Solution
1) read the value in render function not in useEffect