In React applications, data is typically fetched asynchronously from servers or databases. This means components render first, and data arrives later. In this article, we simulate this behavior using mock data and a delayed Promise to mimic real-world API fetching.
We start by creating a function that returns a Promise with sample data after a delay:
const getAsyncStories = () =>
new Promise((resolve) =>
setTimeout(() => resolve({ data: { stories: initialStories } }), 2000)
);This function mimics a network request that resolves after 2 seconds.
In the App component, we initialize the list as an empty array and use useEffect to load data:
const [stories, setStories] = React.useState([]);
React.useEffect(() => {
getAsyncStories().then(result => {
setStories(result.data.stories);
});
}, []);The empty dependency array ensures the effect runs only once when the component mounts.
Initially, the list is empty and nothing is rendered. After 2 seconds, the Promise resolves, the state updates, and the component re-renders to display the loaded stories.
This article showed how to simulate asynchronous data loading in React using Promises and useEffect. It’s a foundational technique for connecting to real APIs and managing dynamic data in user interfaces.