advanced patterns with setState in React Functional Components with useEffect
I've been researching this but I'm not sure how to approach I'm converting an old project and I'm working with an unexpected behavior when trying to update state in a React functional component using `useEffect`. I have a component that fetches data from an API and updates the state based on that data. However, I noticed that the state doesn't seem to update as expected when I log it immediately after calling the `setState` function. Here's a simplified version of my code: ```javascript import React, { useEffect, useState } from 'react'; const MyComponent = () => { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { const fetchData = async () => { try { const response = await fetch('https://api.example.com/data'); const result = await response.json(); setData(result); console.log('Data set:', result); // Logs the fetched data } catch (behavior) { console.behavior('behavior fetching data:', behavior); } finally { setLoading(false); } }; fetchData(); }, []); useEffect(() => { console.log('Updated data:', data); // Expected to log the updated data }, [data]); if (loading) return <div>Loading...</div>; return <div>{JSON.stringify(data)}</div>; }; export default MyComponent; ``` In the second `useEffect`, I am trying to log the updated `data` after it is set. However, it seems that the log doesn't show the expected value immediately after `setData(result)`. I expected that the state would be updated immediately, but instead, I see `null` or the previous state being logged. I've tried placing the log statement directly after `setData(result)` and within the second `useEffect`, but the scenario continues. Is this due to the asynchronous nature of `setState`, or is there something else I'm missing? I am using React 17.0.2. Any insights would be appreciated. The stack includes Javascript and several other technologies. Any feedback is welcome! I'm on Ubuntu 20.04 using the latest version of Javascript. Thanks for taking the time to read this!