08/05/25

Single responsability principle

In React, this can be applied like so:

A Component with SRP (Single Responsibility Principle)

Imagine you need to create a screen that fetches data from an API. This screen needs to:

That means it currently has three different responsibilities, so you can break it down like this:

1. First, fetch the data – the best way to do this (if you're not using SSR) is with a custom hook:

// use-user.ts export function useUser() {
  const [user, setUser] = useState(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetch('/api/user')
      .then((res) => res.json())
      .then((data) => {
        setUser(data)
        setLoading(false)
      })
  }, [])

  return { user, loading }
}

2. Present the fetched data – now that you have the data, you can create a component just to display it. Remember: one responsibility only.

// user-details.tsx type Props = {
  user: { name: string; email: string }
}

const UserDetails = ({ user }: Props) => (
  <div>
    <h1>{user.name}</h1>
    <p>{user.email}</p>
  </div>
)

3. Orchestrate the screen and the fetched data – now you can orchestrate the presentation like this. Notice that the responsibility here is to "connect the dots" between useUser and UserDetails.

That’s why the loading state is handled here—it’s part of the orchestration. The user object is passed as a prop to UserDetails.

// user-profile.tsx import { useUser } from './use-user' import { UserDetails } from './user-details' function UserProfile() {
  const { user, loading } = useUser()

  if (loading) return <p>Loading...</p>

  return <UserDetails user={user} />
}

Benefits:

But of course, none of this works if you don’t practice—so go ahead and open up VSCode!