'Getting initial state instead of the updated state value React useState

Im trying to update my usestate funtion but im always getting 2 values , the initial state and updated state ,the reason why I cant get the proper values for my variables , how can I fix this? I only wanted the 2nd(updated value) on rerender

const userexist = JSON.parse(localStorage.getItem('userpersist'))
const [user,setUser]=useState(null)

useEffect(() => {


    
    if (userexist){

      const fetchComments=async()=>{
      const response=await apiClient('/getuser');
      
      setUser(response.data) 
      setfirstName(response.data.firstName)
      setlastName(response.data.lastName)   
      }

      fetchComments();

     
        
    }else{
        console.log('no user')
    }

    
  }, [])

  useEffect(() => {
    console.log(user)
  }, [user])

the result of console log are

null

the response.data



Solution 1:[1]

useEffect will always run twice even if the dependencies array is empty. So in your case on the first render logs the value of the user on his initial state that's null and then renders again and shows you the new state.

Check this other SO answer for better explanation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jcobo1