Accepted answer

Setting a state is async in nature. Your console.log will always print the previous value of state. You can use useEffect to get the updated value of state everytime it changes -

useEffect(() => { console.log("value of state is", state)}, [state] // dependancy array//)


Try using the state updater function. If you pass a function to setState, React will call it with the actual state:

setState(actualState => {
    return [data, ...actualState]

Related Query

More Query from same tag