1. Direct Props Passing:
interface AddressInfoProps { cartItems: CartItem[]; discountPrice: number; } const AddressInfo: React.FC<AddressInfoProps> = ({ cartItems, discountPrice }) => { // Component implementation };
2. Navigation Route Parameters:
import { useRoute, RouteProp } from '@react-navigation/native'; type AddressInfoRouteProp = RouteProp<{ AddressInfo: { cartItems: CartItem[]; discountPrice: number; }; }, 'AddressInfo'>; const AddressInfo: React.FC = () => { const route = useRoute<AddressInfoRouteProp>(); const { cartItems, discountPrice } = route.params; // Component implementation };
Option 1 is simpler, but it lacks built-in mechanisms to persist state when navigating back and forth between screens. You must always explicitly pass the parameters, meaning the developer is responsible for state persistence. Use it when the component is part of a larger component hierarchy where the parent already has the necessary data to pass down.
Use route parameters (Option 2) when the component represents a screen in your navigation flow—i.e., when backward and forward navigation is expected. With Option 2, the React Native navigation system handles state automatically. If the user navigates to another page and then presses the back button, the screen will re-render with its previous state.
Other options:
Context API: Best for data needed by many components at different nesting levels, but avoid for frequently changing data as it can cause unnecessary re-renders
State Management Libraries (Redux, MobX, Zustand, Jotai): Best for complex applications with lots of shared state and interactions between different parts of the app
URL Parameters: Best for web applications where maintaining bookmarkable state is important
Local Storage: Best for persisting data between app sessions like login status
No comments:
Post a Comment