In this lesson, you will learn how to extract your core business rules from your UI components to ensure your app logic remains pure, testable, and independent of React Native.
The Problem: "View-Locked" Logic
When you are building a mobile app, it is tempting to write your calculations, data validation, and core algorithms directly inside your components or hooks. For example, you might write a tax calculation function right inside a TaxCalculatorScreen.tsx file.
The problem? That code is now "glued" to React. If you want to test that calculation, you have to spin up a full testing environment that understands React components. Furthermore, if you ever wanted to reuse that same logic in a backend Node.js service or a different framework, you wouldn't be able to because it is tangled up with useState and useEffect.
The Solution: Pure Logic Modules
To solve this, we decouple our business logic into "Pure JavaScript/TypeScript Modules." These are simply files that contain functions that take inputs and return outputs without ever touching React hooks or UI elements.
Instead of writing a hook that calculates a discount, create a file named discountService.ts:
// discountService.ts (Pure Business Logic)
export const calculateTotalWithDiscount = (price: number, discount: number): number => {
if (price < 0) return 0;
return price - (price * (discount / 100));
};
By keeping this function "pure," you can import it into any React component easily:
// DiscountScreen.tsx
import { calculateTotalWithDiscount } from './services/discountService';
const DiscountScreen = () => {
const finalPrice = calculateTotalWithDiscount(100, 20);
return <Text>Total: {finalPrice}</Text>;
};
Why This Matters
- Platform Portability: Your
discountService.tsdoesn't care if it is running on iOS, Android, or a web server. - Simplified Testing: You can write unit tests for your logic without mocking the entire React Native environment. You are testing plain functions, which are much faster and less prone to breaking when your UI changes.
- Cleaner Code: Your components stay focused on what they do best: displaying the UI and handling user input, while your services handle the "brain" of the application.
Key Takeaway: By isolating business logic into pure, non-UI modules, you create a portable codebase that is significantly easier to test and maintain across any platform.