Thanks to visit codestin.com
Credit goes to coreui.io

How to fetch data in React with fetch API

Fetching data from APIs is fundamental for building dynamic React applications that display real-time information from external sources. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented countless data fetching patterns in production React components over 25 years of development. From my expertise, the most reliable approach is using the native fetch API inside useEffect with proper cleanup and error handling. This ensures data loads when components mount and prevents memory leaks from cancelled requests.

Use fetch API inside useEffect to load data when component mounts.

const [data, setData] = useState(null)
const [loading, setLoading] = useState(true)

useEffect(() => {
  fetch('/api/users')
    .then(response => response.json())
    .then(setData)
    .finally(() => setLoading(false))
}, [])

Here useEffect runs the fetch request when the component mounts, using the empty dependency array []. The fetch promise chain converts the response to JSON and updates the data state. The finally() block ensures loading state is cleared regardless of success or failure, providing consistent UI feedback.

Best Practice Note:

This is the same data fetching pattern we use in CoreUI React components for reliable API integration. Always handle loading and error states, and consider implementing request cleanup with AbortController to prevent memory leaks when components unmount during pending requests.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
What are the three dots `...` in JavaScript do?
What are the three dots `...` in JavaScript do?

How to Fix “Sass @import Rules Are Deprecated and Will Be Removed in Dart Sass 3.0.0.”
How to Fix “Sass @import Rules Are Deprecated and Will Be Removed in Dart Sass 3.0.0.”

How to migrate CoreUI React Templates to Vite
How to migrate CoreUI React Templates to Vite

How to replace all occurrences of a string in JavaScript?
How to replace all occurrences of a string in JavaScript?

Answers by CoreUI Core Team