09:41:00

Merancang Arsitektur Aplikasi Frontend yang Scalable dengan Feature-Sliced Design (FSD)

Bagaimana Feature-Sliced Design menetapkan batas satu arah yang tegas, mencegah import yang ruwet seperti spageti, dan membantu tim React dan Next.js skala enterprise tetap rapi saat tumbuh.

Diterbitkan
Waktu baca
8 menit baca
  • architecture
  • react
  • fsd
Di halaman ini

Begitu codebase frontend makin kompleks—sudah ratusan component, custom hook, global store, dan API client—struktur folder tradisional yang dikelompokkan berdasarkan jenis file (components/, hooks/, utils/, services/) akhirnya runtuh oleh bebannya sendiri.

Engineer jadi menghabiskan waktu berharga hanya untuk mencari di mana logika domain tertentu berada. Circular dependency yang halus pelan-pelan menyusup ke dalam import, dan me-refactor satu kebutuhan bisnis saja berisiko merusak fitur lain yang sama sekali tidak berhubungan.

Feature-Sliced Design (FSD) menyelesaikan masalah ini dengan menghadirkan kerangka arsitektur yang berpijak pada hierarki layer yang eksplisit, high cohesion, dan low coupling.


Hierarki Layer di FSD

Dalam Feature-Sliced Design, kode dibagi ke dalam layer-layer standar yang diurutkan dari abstraksi tertinggi ke abstraksi terendah.

Ada satu aturan dasar yang mengatur arsitektur ini: Sebuah modul di layer tertentu hanya boleh meng-import dari layer yang berada tepat di bawahnya, tidak pernah dari layer di atasnya atau dari samping di layer yang sama.

text
┌─────────────────────────────────────────────────────────┐
│  1. App       (Providers, global router, global styles) │
├─────────────────────────────────────────────────────────┤
│  2. Pages     (Full route views composed of widgets)    │
├─────────────────────────────────────────────────────────┤
│  3. Widgets   (Self-contained composite UI sections)    │
├─────────────────────────────────────────────────────────┤
│  4. Features  (User interactions delivering value)      │
├─────────────────────────────────────────────────────────┤
│  5. Entities  (Business domain models, types, stores)   │
├─────────────────────────────────────────────────────────┤
│  6. Shared    (UI atoms, Axios client, helper utils)    │
└─────────────────────────────────────────────────────────┘

Contoh Praktis: Membangun Sebuah Domain Slice

Mari kita lihat bagaimana sebuah slice di layer entities disusun, lengkap dengan public API khusus (index.ts), state management Zustand yang ketat, dan service API Axios yang terisolasi.

Perhatikan bagaimana store mengelola indikator loading dengan rapi, sehingga UI component tetap murni deklaratif:

typescript
/**
 * src/entities/user-profile/api/userProfileService.ts
 */
import { apiClient } from '@/shared/api/apiClient'
import type { ApiResponse } from '@/shared/api/http'
import type { UserProfile } from '../model/userProfile.types'

export const userProfileService = {
  getProfileById: async (userIdentifier: string): Promise<UserProfile> => {
    const { data: apiResponse } = await apiClient.get<ApiResponse<UserProfile>>(
      `/users/${userIdentifier}/profile`,
    )

    return apiResponse.data
  },

  updatePreferences: async (
    userIdentifier: string,
    updatedPreferences: Record<string, boolean>,
  ): Promise<UserProfile> => {
    const { data: apiResponse } = await apiClient.patch<ApiResponse<UserProfile>>(
      `/users/${userIdentifier}/preferences`,
      { preferences: updatedPreferences },
    )

    return apiResponse.data
  },
}
typescript
/**
 * src/entities/user-profile/model/userProfileStore.ts
 */
import { create } from 'zustand'
import { userProfileService } from '../api/userProfileService'
import type { UserProfile } from './userProfile.types'

interface UserProfileState {
  currentProfile: UserProfile | null
  isFetchingProfile: boolean
  profileErrorMessage: string | null
  loadUserProfile: (userIdentifier: string) => Promise<void>
}

export const useUserProfileStore = create<UserProfileState>((set) => ({
  currentProfile: null,
  isFetchingProfile: false,
  profileErrorMessage: null,

  loadUserProfile: async (userIdentifier: string) => {
    set({ isFetchingProfile: true, profileErrorMessage: null })

    try {
      const resolvedProfile = await userProfileService.getProfileById(userIdentifier)
      set({ currentProfile: resolvedProfile })
    } catch (caughtError) {
      set({
        profileErrorMessage:
          caughtError instanceof Error ? caughtError.message : 'Failed to retrieve profile data.',
      })
    } finally {
      set({ isFetchingProfile: false })
    }
  },
}))

Memakainya di Widget lewat Public API

Setiap slice mengekspos satu file index.ts yang berfungsi sebagai batas yang eksplisit. Subfolder internal (api/, model/, ui/) tidak pernah diakses langsung dari luar slice.

Saat menyusun sebuah widget, developer cukup men-destructure state dan action yang dibutuhkan dengan rapi, tanpa perlu menduplikasi selector:

tsx
/**
 * src/widgets/profile-card/ui/ProfileSummaryCard.astro (or .tsx)
 */
import { useEffect } from 'react'
import { useUserProfileStore } from '@/entities/user-profile'
import { Button } from '@/shared/ui/button'

interface ProfileSummaryCardProps {
  userIdentifier: string
}

export const ProfileSummaryCard = ({ userIdentifier }: ProfileSummaryCardProps) => {
  const { currentProfile, isFetchingProfile, profileErrorMessage, loadUserProfile } =
    useUserProfileStore()

  useEffect(() => {
    loadUserProfile(userIdentifier)
  }, [userIdentifier, loadUserProfile])

  if (isFetchingProfile) {
    return (
      <div className="flex h-48 w-full items-center justify-center rounded-2xl border border-neutral-800 bg-neutral-950">
        <span className="text-sm text-neutral-400">Loading user profile...</span>
      </div>
    )
  }

  if (profileErrorMessage) {
    return (
      <div className="rounded-2xl border border-red-500/20 bg-red-950/30 p-6 text-sm text-red-300">
        {profileErrorMessage}
      </div>
    )
  }

  return (
    <section className="flex flex-col gap-4 rounded-2xl border border-neutral-800 bg-neutral-950 p-6">
      <div className="flex items-center gap-4">
        <img
          src={currentProfile?.avatarUrl || '/photo.webp'}
          alt={currentProfile?.fullName || 'User Avatar'}
          className="size-14 rounded-full border border-neutral-700 object-cover"
        />
        <div className="flex flex-col">
          <h2 className="text-lg font-bold text-white">{currentProfile?.fullName}</h2>
          <span className="text-xs text-neutral-400">{currentProfile?.jobTitle}</span>
        </div>
      </div>

      <Button variant="outline" className="mt-2 w-full">
        Edit Preferences
      </Button>
    </section>
  )
}

Panduan Utama untuk Menguasai FSD

  • Wajibkan Import Satu Arah: Jalankan aturan boundary ESLint (eslint-plugin-boundaries) di pipeline CI supaya import horizontal atau terbalik yang melanggar aturan sudah tertangkap sebelum kode di-merge.
  • Jangan Pernah Import dari Sibling: Kalau feature/like-article butuh fungsionalitas dari feature/bookmark-article, turunkan state yang dipakai bersama ke entities/article atau naikkan ke sebuah widget gabungan.
  • Isolasi Public API: Jangan pernah import from '@/entities/user/ui/subfolder/Component'. Selalu import hanya dari @/entities/user.
  • #architecture
  • #react
  • #fsd
  • #typescript

Bagikan

Komentar

Ikut berdiskusi

Masuk dengan GitHub untuk berkomentar di Merancang Arsitektur Aplikasi Frontend yang Scalable dengan Feature-Sliced Design (FSD).

Pip · Asisten AI pribadi

Mau tahu apa hari ini?

Saya Pip. Saya tahu pengalaman, proyek, tulisan, dan cara bekerja sama dengan Saleh.

Jawaban dibuat AI dan bisa keliru.

Lampiran

100%