Back

useEffect

useEffect runs code after the component renders. Use it for fetching data, setting up subscriptions, or anything that needs to happen after the UI appears.

import { useState, useEffect } from 'react'

function UserProfile({ userId }: { userId: number }) {
  const [user, setUser] = useState(null)

  useEffect(() => {
    // Runs after component renders
    fetch(`/api/users/${userId}`)
      .then(res => res.json())
      .then(data => setUser(data))
  }, [userId])  // re-runs when userId changes

  if (!user) return <p>Loading...</p>
  return <p>{user.name}</p>
}

Roadmap