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[]
})
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[]
})
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])