Fetching Data in React Using APIs
Introduction
Most real world React applications need data from a backend server or API.
For example:
- User Details
- Product Lists
- Blog Posts
- Weather Data
React provides the useEffect hook to handle these side effects like fetching data.
What is useEffect ?
useEffect is a React Hook used to run code after a component renders.
Common uses of useEffect
- Fetch data from APIs
- Update the document title
- Add event listeners
- Run code when a component loads
Why Use useEffect for API Calls?
When a component loads,
- React first renders the UI
- Then useEffect runs
- API data is fetched
- UI updates with new data
Basic Syntax of useEffect
- The empty array [] means run the code only once when the component loads
Example: Fetching Data from an API
Let's fetch users from a free API
Step by Step Example
1. useState
2. useEffect
3. fetch()
4. Rendering the data
Using Async/Await
- Cleaner
- Easier to read
- Recommended for modern React
Handling Loading State
- Forgetting the dependency array
- Calling API outside useEffect
- Updating state without checking component lifecycle
When to use useEffect for APIs?
Use useEffect when,
- Data should load on page load
- Data depends on props or state
- You need to sync UI with external data
Comments
Post a Comment