0

I expect it show Array[1,2,3] in termeral,but it's not.Can someone help me figure out!

const [data,setData]=useState([]);
useEffect(()=>{
  setData([1,2,3]);
  console.log(data);//show Array[] 
})
Chen Chen
  • 3
  • 3
  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – David Scholz Jun 06 '22 at 20:32

1 Answers1

0

First you wanna make sure you are purposefully omitting your dependencies array in useEffect. Currently you are letting react auto generate your dependency array, which I believe would be [data, setData]. Anytime these values changed your effect would be called, meaning that if the value of data is changed your effect is called and data would become [1,2,3] again.

If your desired result is to call this effect at first render pass an empty dependency array to the effect:

useEffect(()=>{
  setData([1,2,3]); 
},[])

If you want to log data whenever it changes useEffect with data as its dependency

useEffect(()=>{
  console.log('data has been updated!');
  console.log(data);
},[data])
PhantomSpooks
  • 2,877
  • 2
  • 8
  • 13