Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React hooks - wait until the state has been updated

I'm using the useState() hook, and I've found that my app has a bug, because setting the value is asynchronous. So if I have code like this:

 const [data, setData] = useState([])
  useEffect(() => {
    const getData = async () => {
      const res = await fetchData()
      console.log(data); // []
      setData(res.data.hits);
      console.log(res.data.hits); // Array full of objects
      console.log(data); // Still []
    }
    getData()
  }, [fetchData]);

How can I execute some specific logic only when the new state has actually been set?

like image 891
gfels Avatar asked Apr 02 '26 11:04

gfels


1 Answers

You can use the useEffect hook:

useEffect(() => {
   //your code
}, [data]);

That will trigger what is inside every time data changes.

like image 65
Nico_ Avatar answered Apr 04 '26 01:04

Nico_



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!