iTranslated by AI
Refactoring a 1,200-Line React Native Monolithic Component into 22 Modular Files
Introduction
In my React Native (Expo) app, the account screen component grew into a monolithic file exceeding 1,200 lines. With over 30 useState hooks, 12 sub-screens, 9 modals, and 4 useEffect hooks concentrated in one file, any change required understanding the entire codebase.
In this article, I will share the design decisions and implementation techniques used to refactor this component into 22 separate files.
Key Takeaways:
- Pattern for replacing boolean sprawl with exclusive control via Union Types
- Criteria for dividing responsibilities in custom hooks
-
useCallbackstrategy to makeReact.memoeffective - Lazy loading of sub-screens using
React.lazy
Pre-Refactoring Status
First, let's look at how challenging it was.
// AccountScreen.tsx — Monolithic component with over 1200 lines
export const AccountScreen: React.FC<Props> = ({ onClose }) => {
// 30+ useState...
const [user, setUser] = useState<User | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [showFAQScreen, setShowFAQScreen] = useState(false);
const [showContactUsScreen, setShowContactUsScreen] = useState(false);
const [showMessageScreen, setShowMessageScreen] = useState(false);
const [showDebugMenu, setShowDebugMenu] = useState(false);
const [showSignInModal, setShowSignInModal] = useState(false);
const [showNotificationModal, setShowNotificationModal] = useState(false);
const [showTagEditorModal, setShowTagEditorModal] = useState(false);
// ...and 20+ more
// 4 useEffects...
useEffect(() => { /* Watch user data */ }, []);
useEffect(() => { /* Check LINE integration */ }, []);
useEffect(() => { /* Check unread messages */ }, []);
useEffect(() => { /* Check auth state */ }, [dep]);
// 12 sub-screen branches using if statements...
if (showDebugMenu) return <DebugMenuScreen onClose={() => setShowDebugMenu(false)} />;
if (showFAQScreen) return <FAQScreen onClose={() => setShowFAQScreen(false)} />;
if (showContactUsScreen) return <ContactUsScreen onClose={...} />;
// ...and 9 more
// Main screen (300-line IIFE pattern)
return (
<SafeAreaView>
{(() => {
// 700 lines of JSX here...
// 9 modals here...
})()}
</SafeAreaView>
);
};
Issues:
| Issue | Impact |
|---|---|
| 30+ boolean states | Screens that should be exclusive could be true simultaneously |
| 1 file, 1200 lines | Difficulty identifying changes, high review burden |
| IIFE pattern | A workaround for declaring local variables inside JSX |
| 4 mixed useEffects | Hard to track which side effect affects which state |
Overview of the Structure
Here is the file structure after refactoring.
types/
account.ts # Union type definitions
hooks/account/
useAccountUser.ts # User data listener
useAccountAuth.ts # Auth status + signOut
useLineLink.ts # LINE integration check
useUnreadMessages.ts # Unread messages
useAccountNavigation.ts # Screen navigation management
components/account/
AccountScreen.tsx # Main container (assembling hooks)
AccountHeader.tsx # Header
AccountLoadingView.tsx # Loading view
AccountSubScreenRenderer.tsx # Sub-screen routing
AccountModals.tsx # Integrated 9 modals
styles.ts # Shared styles
sections/
LineLinkSection.tsx # LINE integration banner
MessagesSection.tsx # Messages
SubscriptionSection.tsx # Subscription
SettingsSection.tsx # Settings (11 items)
OtherSection.tsx # FAQ / Terms of Service, etc.
UserInfoSection.tsx # User info
ReferralCodeSection.tsx # Referral code
DebugSection.tsx # Debug
┌─────────────────────────────────────────────┐
│ AccountScreen.tsx │
│ ┌─────────────┐ ┌──────────────────────┐ │
│ │ Hooks │ │ Components │ │
│ │ ┌─────────┐ │ │ ┌────────────────┐ │ │
│ │ │ User │ │ │ │ Header │ │ │
│ │ │ Auth │ │ │ │ SubScreen │ │ │
│ │ │ LineLink│ │ │ │ Renderer │ │ │
│ │ │ Unread │ │ │ │ Sections (×8) │ │ │
│ │ │ Nav │ │ │ │ Modals │ │ │
│ │ └─────────┘ │ │ └────────────────┘ │ │
│ └─────────────┘ └──────────────────────┘ │
└─────────────────────────────────────────────┘
Design Points
Point 1: Boolean Sprawl → Exclusive Control via Union Types
In the original code, 12 sub-screens were managed using 12 individual boolean states.
// ❌ Before: Screens that should be exclusive managed as independent booleans
const [showFAQScreen, setShowFAQScreen] = useState(false);
const [showContactUs, setShowContactUs] = useState(false);
const [showDebugMenu, setShowDebugMenu] = useState(false);
// ...and 9 more
This structure has a fundamental problem where multiple screens could be true at the same time. Since, in reality, these sub-screens are exclusive (only one can be open at a time), they can be expressed using Union Types.
// ✅ After: Type-level guarantee for exclusive states using Union Types
type AccountSubScreen =
| 'none'
| 'faq'
| 'contactUs'
| 'debugMenu'
| 'messageScreen'
| 'linkLine'
| 'onboarding'
| 'userNameEdit'
| 'accountManagement'
// ...
type AccountModalType =
| 'none'
| 'signIn'
| 'notification'
| 'tagEditor'
| 'speech'
| 'targetLanguage'
// ...
This makes the navigation management hook much simpler.
// hooks/account/useAccountNavigation.ts
export function useAccountNavigation() {
const [activeSubScreen, setActiveSubScreen] = useState<AccountSubScreen>('none');
const [activeModal, setActiveModal] = useState<AccountModalType>('none');
const openSubScreen = useCallback((screen: AccountSubScreen) => {
setActiveSubScreen(screen);
}, []);
const closeSubScreen = useCallback(() => {
setActiveSubScreen('none');
}, []);
const openModal = useCallback((modal: AccountModalType) => {
setActiveModal(modal);
}, []);
const closeModal = useCallback(() => {
setActiveModal('none');
}, []);
return {
activeSubScreen, activeModal,
openSubScreen, closeSubScreen,
openModal, closeModal,
};
}
Point 2: Criteria for Dividing Domain-Specific Hooks
The 4 useEffect hooks that were intermingled in a single file have been split based on the independence of their data sources.
| Hook | Responsibility | Data Source |
|---|---|---|
useAccountUser |
User data monitoring + plan status | Firestore listener |
useAccountAuth |
Auth status check + signOut | Firebase Auth |
useLineLink |
LINE integration check | Firestore (accounts) |
useUnreadMessages |
Unread message check | MessageService |
useAccountNavigation |
Navigation management | Local state only |
// hooks/account/useAccountUser.ts
export function useAccountUser() {
const [user, setUser] = useState<User | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [planStatus, setPlanStatus] = useState('');
useEffect(() => {
const unsubscribe = UserService.listenUser(async (userData) => {
setUser(userData);
setIsLoading(false);
if (userData) {
// Plan status calculation
const isPremium = UserUtils.isPremiumUser(userData);
setPlanStatus(isPremium ? 'Active' : 'Unsubscribed');
}
});
return () => unsubscribe();
}, []);
return { user, isLoading, planStatus };
}
Point 3: Organizing Sub-screens with Switch Statements + React.lazy
The chain of 12 if statements was replaced by a switch statement and separated into a routing component.
// ❌ Before: Chain of if statements
if (showDebugMenu) return <DebugMenuScreen onClose={() => setShowDebugMenu(false)} />;
if (showFAQScreen) return <FAQScreen onClose={() => setShowFAQScreen(false)} />;
if (showContactUs) return <ContactUsScreen onClose={() => setShowContactUs(false)} />;
// ...and 9 more
// ✅ After: switch statement + React.lazy
const LazyDebugMenu = React.lazy(() =>
import('@/components/DebugMenuScreen').then(m => ({ default: m.DebugMenuScreen }))
);
const LazyOnboarding = React.lazy(() =>
import('@/components/onboarding/OnboardingFlow').then(m => ({ default: m.OnboardingFlow }))
);
export function SubScreenRenderer({ activeSubScreen, onClose }: Props) {
switch (activeSubScreen) {
case 'debugMenu':
return (
<Suspense fallback={<LoadingView />}>
<LazyDebugMenu onClose={onClose} />
</Suspense>
);
case 'faq':
return <FAQScreen onClose={onClose} />;
case 'contactUs':
return <ContactUsScreen onClose={onClose} />;
// ...
case 'none':
return null;
}
}
Implementation Tips
Tip 1: The useCallback Strategy to "Really" Make React.memo Work
Even if you wrap a section component in React.memo, it is meaningless if you pass a new function reference from the parent on every render.
// ❌ React.memo does not work: New function created on every render
<SettingsSection
onOpenTextSize={() => openSubScreen('textSize')}
onOpenWidget={() => openSubScreen('widgetColor')}
/>
// ✅ React.memo works: Reference stabilized with useCallback
const openTextSize = useCallback(() => openSubScreen('textSize'), [openSubScreen]);
const openWidget = useCallback(() => openSubScreen('widgetColor'), [openSubScreen]);
<SettingsSection
onOpenTextSize={openTextSize}
onOpenWidget={openWidget}
/>
The key is that openSubScreen itself must also be stabilized with useCallback. It is meaningless unless the entire dependency chain is stabilized.
// Inside useAccountNavigation.ts
const openSubScreen = useCallback((screen: AccountSubScreen) => {
setActiveSubScreen(screen); // setState is always a stable reference
}, []);
Tip 2: Maintaining Backward Compatibility via Re-export
Splitting a massive component means you would typically need to update every file that imports it. This can be avoided using re-export.
// components/AccountScreen.tsx (Original file)
// 1200 lines → 1 line
export { AccountScreen } from './account/AccountScreen';
With this, export * from './AccountScreen' in components/index.ts and imports from other files require zero changes.
Tip 3: Granularity of Section Components
The division granularity for sections was determined by "visual grouping within the ScrollView."
// AccountScreen.tsx (Main container) only handles assembly
<ScrollView>
{showLineLinkBanner && <LineLinkSection onOpen={openLinkLine} />}
<MessagesSection hasUnread={hasUnread} onOpen={openMessages} />
{user && <SubscriptionSection user={user} planStatus={planStatus} />}
<SettingsSection onOpenModal={openModal} />
<OtherSection onOpenFAQ={openFAQ} onOpenContactUs={openContactUs} />
{user?.id && <UserInfoSection user={user} />}
<ReferralCodeSection onOpen={openReferralCode} />
{isDev && <DebugSection onSignOut={handleSignOut} />}
</ScrollView>
Each section is wrapped in React.memo, preventing re-renders unless the props relevant to that section change.
export const SettingsSection = React.memo(function SettingsSection({
onOpenModal,
onOpenTextSize,
onOpenWidget,
}: Props) {
return (
<View>
<Text>Settings</Text>
<Card>
<MenuItem testID="tags_button" icon="local-offer" label="Tags"
onPress={() => { logAnalytics('tagEditor'); onOpenModal('tagEditor'); }} />
<MenuItem testID="notification_button" icon="notifications" label="Notification"
onPress={() => onOpenModal('notification')} />
{/* ...11 items */}
</Card>
</View>
);
});
Troubleshooting: Removing the IIFE Pattern
The original code used IIFE (Immediately Invoked Function Expressions) within JSX to declare local variables.
// ❌ Before: IIFE pattern — 300 lines trapped inside a function within return
return (
<SafeAreaView>
{(() => {
const currentUser = auth().currentUser;
const userId = currentUser?.uid || 'N/A';
const email = currentUser?.email;
return (
<>
<Header />
<ScrollView>
{/* 700 lines of JSX... */}
</ScrollView>
{/* 9 modals... */}
</>
);
})()}
</SafeAreaView>
);
// ✅ After: Local variables are declared in the component body
const userId: string = currentUser?.uid || t('unavailable');
const userEmail = currentUser?.email ?? undefined;
return (
<SafeAreaView>
<AccountHeader onClose={onClose} />
<ScrollView>
{/* Split into section components */}
</ScrollView>
<AccountModals activeModal={activeModal} onClose={closeModal} />
</SafeAreaView>
);
The only reason IIFE was needed was to use const inside return. Moving these to the component body resolves this naturally.
Summary
List of Design Decisions
| Decision | Selection | Reason |
|---|---|---|
| Managing 30 booleans | 2 Union Types | Ensures exclusive state at the type level |
useEffect split criteria |
By data source | Keeps independent side effects in separate hooks |
| Sub-screen branching | switch + React.lazy | Converts 12 chained if statements into type-safe routing |
| Section split granularity | Visual grouping | Each section in ScrollView is a component |
| Compatibility with imports | Re-export | Minimizes the number of files changed |
| Performance optimization | React.memo + useCallback | Prevents unnecessary re-renders of all sections |
Learnings
- Exclusive states should be expressed as Union Types, not booleans — You can enforce the restriction that they "cannot be true simultaneously" using types.
-
React.memois only effective when paired withuseCallback— It is meaningless unless the entire dependency chain is stable. - Re-export is a friend of large-scale refactoring — It allows you to change the file structure without updating imports.
- The IIFE pattern is a sign of design distortion — If you need to declare variables inside JSX, it is time to reconsider your component architecture.
Refactoring Checklist
- If there are 3 or more exclusive booleans, integrate them into a Union Type.
-
Confirm that each
useEffecthas an independent data source. -
If using
React.memo, ensure all functions in the props are stabilized withuseCallback. - Change the original file to use re-export and verify that existing imports are not broken.
-
Confirm with
grepthat alltestIDs have been preserved in their new locations.
Discussion