Course contentsShow
← React
Lesson 1576 of 2,39639. Server Components in PracticeFree lesson

Fetching Data Directly in Components

Server components can fetch data from databases or APIs without useEffect or state management.

Fetching Data Directly in Components

What you'll learn: How server components eliminate useEffect and useState for data fetching by allowing direct async operations inside component bodies.

The Old Way vs The New Way

In traditional React, fetching data meant wrapping everything in useEffect, managing loading states with useState, and dealing with complex dependency arrays. Server components throw that entire pattern out the window.

Because server components run only on the server, they can be async functions that directly await data—just like any backend code. No hooks, no state management, no useEffect lifecycle juggling.

How It Works

Instead of this traditional pattern:

// Old client component pattern
function UserProfile({ id }) {
  const [user, setUser] = useState(null);
  
  useEffect(() => {
    fetch(`/api/users/${id}`)
      .then(res => res.json())
      .then(setUser);
  }, [id]);
  
  return user ? <div>{user.name}</div> : <div>Loading...</div>;
}

You write this in a server component:

// New server component pattern
async function UserProfile({ id }) {
  const user = await db.users.findById(id);
  
  return <div>{user.name}</div>;
}

Notice: no hooks, no state, no loading UI. The component itself is the data fetching logic. It's sequential, readable, and runs entirely on the server before any HTML reaches the browser.

Why This Changes Everything

This isn't just cleaner syntax—it's a fundamental shift. You're no longer building an API endpoint that your frontend calls. You're accessing your database directly in the component that needs the data. The component waits for the data, then renders. Simple.

Key Takeaway: Server components collapse data fetching into the component itself using async/await, eliminating the useEffect + useState pattern entirely for server-rendered data.