You are on page 1of 2

UseState

-> 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.
->

PUSH METHOD IN USESTATE

const [theArray, setTheArray] = useState(initialArray)


-> when you want to add a new element, you use that function and pass in the new
array or a function that will create the new array, since state updates are asynchronous
and sometimes batched.

setTheArray(oldArray=>[...oldArray, newElement])

-> for certain user event like click we can use


setTheArray([...oldArray, newElement])

Examples
const [theArray, setTheArray] = useState(initialArray)
const [theObject, setTheObject] = useState(initialObject)

1) Push element at the end of array.


setTheArray(prevArray => [...prevArray, newValues])

2) Push/update element at the end of object


setTheObject(prevState => ({...prevState, currentOrNewKey: newValue }));

3) Push/update element at the end of array of objects


setTheArray( prevState => [...prevState, {currentOrNewKey: newValue }));

4) Push the element at end of objects of arrays


let specificArrayInObject= theObject.array.slice()
specificArrayInObject.push(newvalue)
const newObj = {...theObject, [event.target.anem]:specificArrayInobject };
setTheObject(newObj)
Caling Data Asynchronously from useEffect

-> useEffect(()=> {
async function getLastData(){
await getLast();
}
})

Asynchronous nature of setState


https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-
change-immediately

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

2) Add the dependency array or variable in useEffect

3) Use a mutable reference (useRef)

useState with previous state


-> when you need to update state value based on previous state value always go with
the safer option of passing a function that will set the new state value

useState with object


-> useState does not automatically merge and update the state object.
-> In class it automatically merge.
SetName({...name, firstName: e.target.value})
-> Copy every property in the name object and then just overwrite the first name field
with a different value.

UseState with array

You might also like