Passing Parameters Between Screens in React Native
Course: React Native Training
Topic: Passing Parameters Between Screens
Course Link: React Native Training at JustAcademy
Demo Link: Register for a Course Demo
JustAcademy Website: Visit JustAcademy
1. Introduction to Passing Parameters Between Screens
In React Native applications, users frequently move from one screen to another. Often, the destination screen needs information from the screen the user came from. Passing parameters allows developers to transfer this information through the navigation system.
For example, in an e-commerce application, a user selects a product from a product list. When the user opens the Product Details screen, the application needs to know which product was selected. The product ID can be passed as a navigation parameter so the destination screen can retrieve and display the correct product information.
React Navigation supports passing parameters through methods such as navigation.navigate() and navigation.push(). The destination screen can access the received values through route.params.
1.1 What Are Navigation Parameters?
Navigation parameters, also called route parameters or route params, are values associated with a route when navigating to a screen. They help the destination screen determine which information to display or which screen-specific options to apply.
Common examples include:
- Product IDs and category IDs.
- User IDs for displaying profiles.
- Names, titles, and selected item identifiers.
- Search queries and filter settings.
- Sorting preferences and pagination values.
- Initial values for a form.
- Identifiers used to retrieve information from an API.
1.2 Real-World Example
Consider a shopping application with the following screens:
- Home Screen: Displays a list of products.
- Product Details Screen: Displays details about the selected product.
- Checkout Screen: Continues the purchase process using the selected product or cart information.
When a user selects a product, the Home Screen can pass the product ID to the Product Details Screen. The destination screen can then retrieve the latest product information using that ID.
1.3 Learning Objectives
After completing this topic, learners will be able to:
- Understand navigation parameters and their purpose.
- Pass parameters using React Navigation methods.
- Receive parameters through
route.params.
- Access route parameters using the
useRoute() hook.
- Configure default parameters using
initialParams.
- Update route parameters using
navigation.setParams().
- Pass parameters to nested screens.
- Return information to a previous screen.
- Handle optional and missing parameters safely.
- Apply best practices for parameter handling in real-world applications.
2. Understanding React Navigation
React Navigation is a library used to manage navigation in React Native applications. It provides tools for moving between screens and maintaining navigation state.
2.1 Important Navigation Concepts
| Concept |
Description |
| Screen |
A React component that represents a page or interface in an application. |
| Route |
A registered destination managed by a navigator. |
| Navigation object |
Provides methods for moving between routes and interacting with navigation state. |
| Route object |
Contains information about the current route, including its name and parameters. |
| Route parameters |
Values passed to a destination screen during navigation. |
| Navigator |
Manages a collection of routes and determines how users move between screens. |
| NavigationContainer |
Provides the navigation context for the root navigation tree in a standard React Navigation application. |
2.2 How Parameter Passing Works
- The user presses a button or selects an item.
- The source screen calls a navigation method.
- The navigation method receives the destination route name and a parameter object.
- React Navigation navigates to the destination screen.
- The destination screen reads the values from its route object.
- The destination screen uses the values to display the appropriate content.
Source Screen
|
| navigation.navigate('Details', { productId: 101 })
v
React Navigation
|
| Passes route parameters
v
Details Screen
|
| Reads route.params.productId
v
Displays the selected product information
3. Prerequisites
Before learning parameter passing, you should understand the following concepts:
- JavaScript variables, objects, and functions.
- React components and JSX.
- React Native components such as
View, Text, and Button.
- React props and state.
- Basic navigation using React Navigation.
- Stack navigator configuration.
4. Installing and Configuring React Navigation
Navigation parameters work with React Navigation navigators. The examples in this lesson use a native stack navigator.
4.1 Install the Required Packages
For an Expo project, install the required packages if they are not already present:
npm install @react-navigation/native
npx expo install react-native-screens react-native-safe-area-context
npm install @react-navigation/native-stack
For a React Native Community CLI project, install the packages using npm and follow the official setup instructions for your platform:
npm install @react-navigation/native
npm install react-native-screens react-native-safe-area-context
npm install @react-navigation/native-stack
For iOS Community CLI projects, install CocoaPods dependencies when required and rebuild the application after adding native dependencies. Use versions compatible with your project's React Native setup.
4.2 Create a Stack Navigator
A stack navigator allows users to move between screens and return to previous screens.
// App.js
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import HomeScreen from './screens/HomeScreen';
import DetailsScreen from './screens/DetailsScreen';
const Stack = createNativeStackNavigator();
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
/>
<Stack.Screen
name="Details"
component={DetailsScreen}
/>
</Stack.Navigator>
</NavigationContainer>
);
}
This configuration registers two screens: Home and Details. The Home screen will pass parameters to the Details screen in the examples below.
5. Passing Parameters Using navigation.navigate()
The navigation.navigate() method navigates to a registered route and can pass an object containing parameters as its second argument.
5.1 Basic Syntax
navigation.navigate('RouteName', {
parameterName: parameterValue,
});
In this syntax:
RouteName is the name of the destination route.
- The second argument contains the parameters.
- Each parameter is represented as a key-value pair.
5.2 Passing a Single Parameter
Suppose the Home screen needs to open a Details screen and pass a product ID.
import React from 'react';
import { View, Text, Button } from 'react-native';
export default function HomeScreen({ navigation }) {
return (
<View>
<Text>Home Screen</Text>
<Button
title="View Product"
onPress={() =>
navigation.navigate('Details', {
productId: 101,
})
}
/>
</View>
);
}
When the user presses the button, React Navigation opens the Details route and passes the value 101 as the product ID.
5.3 Passing Multiple Parameters
You can pass multiple values in the same parameter object.
navigation.navigate('Details', {
productId: 101,
productName: 'Wireless Headphones',
price: 2499,
category: 'Electronics',
});
The destination screen can read each value from route.params.
5.4 Passing Different Data Types
Parameters can include serializable values such as strings, numbers, booleans, arrays, and plain objects when appropriate.
navigation.navigate('Details', {
productId: 101,
productName: 'Wireless Headphones',
isAvailable: true,
tags: ['Audio', 'Wireless'],
discount: {
percentage: 10,
active: true,
},
});
Although multiple data types can be passed, keep navigation parameters small and focused. For large records, pass an identifier and retrieve the full data from an API, cache, or application store.
6. Receiving Parameters Using route.params
React Navigation supplies a route prop to screen components. The route.params property contains the parameters associated with the current route.
6.1 Basic Syntax
export default function DetailsScreen({ route }) {
const { productId } = route.params;
return (
<Text>Product ID: {productId}</Text>
);
}
6.2 Complete Example: Passing a Product ID
Create the following Home screen:
// screens/HomeScreen.js
import React from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
export default function HomeScreen({ navigation }) {
return (
<View style={styles.container}>
<Text style={styles.title}>Home Screen</Text>
<Text>Select a product to view its details.</Text>
<Button
title="View Product 101"
onPress={() =>
navigation.navigate('Details', {
productId: 101,
})
}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
},
title: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 12,
},
});
Create the Details screen:
// screens/DetailsScreen.js
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default function DetailsScreen({ route }) {
const { productId } = route.params;
return (
<View style={styles.container}>
<Text style={styles.title}>Product Details</Text>
<Text>Selected Product ID: {productId}</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
},
title: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 12,
},
});
Expected result: When the user presses View Product 101, the Details screen opens and displays the product ID as 101.
6.3 Reading Multiple Parameters
export default function DetailsScreen({ route }) {
const {
productId,
productName,
price,
category,
} = route.params;
return (
<View>
<Text>Product ID: {productId}</Text>
<Text>Product Name: {productName}</Text>
<Text>Price: ₹{price}</Text>
<Text>Category: {category}</Text>
</View>
);
}
Ensure the source screen passes the same parameter names that the destination screen reads. If the names do not match, the destination screen may receive an undefined value.
7. Handling Optional and Missing Parameters
A screen may sometimes be opened without receiving all expected parameters. Directly accessing a missing value can lead to undefined values or rendering errors if the component assumes the data exists.
7.1 Using Optional Chaining
const productId = route.params?.productId;
Optional chaining checks whether route.params exists before attempting to read productId.
7.2 Providing a Default Value
const productName =
route.params?.productName ?? 'Unknown Product';
The nullish coalescing operator ?? supplies a fallback when the value is null or undefined.
7.3 Complete Example
import React from 'react';
import { View, Text } from 'react-native';
export default function DetailsScreen({ route }) {
const productId = route.params?.productId ?? 'Not provided';
const productName =
route.params?.productName ?? 'Unknown Product';
return (
<View>
<Text>Product Details</Text>
<Text>Product ID: {productId}</Text>
<Text>Product Name: {productName}</Text>
</View>
);
}
Use safe access when parameters are optional. If a parameter is essential, validate it and display an appropriate error or loading state rather than treating invalid data as valid.
8. Setting Default Parameters with initialParams
React Navigation allows developers to define default route parameters through the initialParams option on a screen.
8.1 Example
<Stack.Screen
name="Details"
component={DetailsScreen}
initialParams={{
productId: 101,
productName: 'Default Product',
}}
/>
If the Details screen is opened without explicitly providing those parameters, the configured initial values can be used.
8.2 Overriding Default Parameters
Parameters supplied during navigation can override matching initial parameter values.
navigation.navigate('Details', {
productId: 205,
productName: 'Gaming Keyboard',
});
In this example, the navigation-provided values take precedence over the corresponding defaults. Initial parameters are useful for fallback values, but they do not replace validation for required data.
9. Using the useRoute() Hook
The useRoute() hook from React Navigation provides access to the current route object from a component rendered within the appropriate navigation context.
9.1 Importing useRoute
import { useRoute } from '@react-navigation/native';
9.2 Example
import React from 'react';
import { View, Text } from 'react-native';
import { useRoute } from '@react-navigation/native';
export default function ProductInformation() {
const route = useRoute();
const productId = route.params?.productId;
const productName = route.params?.productName;
return (
<View>
<Text>Product ID: {productId ?? 'Unavailable'}</Text>
<Text>Product Name: {productName ?? 'Unavailable'}</Text>
</View>
);
}
9.3 route.params Versus useRoute()
| Approach |
When to Use It |
({ route }) |
When the screen component receives the route object through its props. |
useRoute() |
When a nested component needs access to the current route through navigation context. |
Both approaches can access the current route's parameters. Prefer the route prop for ordinary screen components when it is already available, and use the hook when it makes component composition more convenient.
10. Updating Parameters with navigation.setParams()
The navigation.setParams() method updates or adds parameters to the current route. New values are merged with existing parameters.
10.1 Basic Syntax
navigation.setParams({
productName: 'Updated Product Name',
});
10.2 Example
import React from 'react';
import { View, Text, Button } from 'react-native';
export default function DetailsScreen({ route, navigation }) {
const productName =
route.params?.productName ?? 'Unknown Product';
return (
<View>
<Text>Product: {productName}</Text>
<Button
title="Update Product Name"
onPress={() =>
navigation.setParams({
productName: 'Updated Headphones',
})
}
/>
</View>
);
}
When the button is pressed, the route parameter is updated, and the component can render the new value.
10.3 Important Considerations
setParams() merges the supplied values with existing parameters.
- Use it for route-related information rather than as a general application state store.
- Use
navigation.setOptions() to update navigation options such as the header title.
- Keep parameters serializable whenever possible.
11. Passing Parameters Using navigation.push()
The navigation.push() method is commonly used with stack navigators. It pushes another route instance onto the stack and can pass parameters to that instance.
11.1 Example
navigation.push('Details', {
productId: 202,
productName: 'Bluetooth Speaker',
});
This can be useful when an application needs to open another instance of a screen with different data, such as moving from one product's details to another product's details.
11.2 navigate() Versus push()
| Method |
Purpose |
navigation.navigate() |
Navigates to a route according to the navigator's behavior. It may focus an existing route or create a route as needed. |
navigation.push() |
Pushes a new route instance onto a stack navigator. |
push() is a stack navigation method. It is not a universal replacement for navigate() in tab or drawer navigation.
12. Passing Parameters Between Nested Navigators
Real applications frequently use nested navigators. For example, a bottom tab navigator may contain a stack navigator, and that stack may contain a Details screen.
12.1 Example Navigation Structure
NavigationContainer
└── BottomTabNavigator
├── HomeTab
│ └── HomeStack
│ ├── HomeScreen
│ └── DetailsScreen
└── ProfileTab
└── ProfileScreen
12.2 Navigating to a Screen Inside a Nested Navigator
If the HomeTab route contains a nested navigator, parameters can be passed to a child screen by specifying the parent route, nested screen name, and parameters.
navigation.navigate('HomeTab', {
screen: 'Details',
params: {
productId: 101,
productName: 'Wireless Headphones',
},
});
This example assumes that HomeTab is a registered route containing a nested navigator and that Details is registered inside it. Adjust route names to match your application.
12.3 Understanding Nested Parameters
- The outer route identifies the parent navigator or screen.
- The
screen property identifies the nested destination.
- The nested
params object contains values intended for that destination.
React Navigation reserves certain parameter names for nested navigation APIs, including screen, params, initial, and state. Avoid using these names for unrelated application data.
13. Passing Data Back to a Previous Screen
Parameters can also be used to return information to a previous screen. For example, a user may create a post on one screen and return to the Home screen with the new post's title.
13.1 Example Workflow
- The Home screen opens the Create Post screen.
- The user enters a post title.
- The Create Post screen returns to Home with the new title.
- The Home screen reads the updated route parameters.
13.2 Home Screen Example
import React, { useEffect } from 'react';
import { View, Text, Button } from 'react-native';
export default function HomeScreen({ navigation, route }) {
const post = route.params?.post;
useEffect(() => {
if (post) {
// Handle the returned post value here.
// For example, update a list or refresh data.
}
}, [post]);
return (
<View>
<Text>Home Screen</Text>
<Text>New Post: {post ?? 'No post created yet'}</Text>
<Button
title="Create Post"
onPress={() => navigation.navigate('CreatePost')}
/>
</View>
);
}
13.3 Create Post Screen Example
The following example uses navigation.popTo(), which is available in current React Navigation stack APIs. It assumes that Home exists earlier in the same stack.
import React, { useState } from 'react';
import { View, TextInput, Button } from 'react-native';
export default function CreatePostScreen({ navigation }) {
const [postTitle, setPostTitle] = useState('');
return (
<View>
<TextInput
value={postTitle}
onChangeText={setPostTitle}
placeholder="Enter post title"
/>
<Button
title="Save Post"
onPress={() => {
navigation.popTo('Home', {
post: postTitle,
});
}}
/>
</View>
);
}
For older React Navigation versions without popTo(), use the return-navigation pattern documented for that version. For complex data updates, a shared state store or data cache may be more appropriate than route parameters.
14. Practical Project: Product List and Product Details
This project demonstrates how to pass product information from a list screen to a details screen. It includes a list of products, a button for each product, and a destination screen that displays the selected product.
14.1 Create the Product List Screen
// screens/ProductListScreen.js
import React from 'react';
import { View, Text, Button, FlatList, StyleSheet } from 'react-native';
const products = [
{ id: '101', name: 'Wireless Headphones', price: 2499 },
{ id: '102', name: 'Bluetooth Speaker', price: 1999 },
{ id: '103', name: 'Smart Watch', price: 3999 },
];
export default function ProductListScreen({ navigation }) {
return (
<View style={styles.container}>
<Text style={styles.title}>Product List</Text>
<FlatList
data={products}
keyExtractor={(item) => item.id}
renderItem={({ item }) => (
<View style={styles.product}>
<Text>{item.name}</Text>
<Text>Price: ₹{item.price}</Text>
<Button
title="View Details"
onPress={() =>
navigation.navigate('ProductDetails', {
productId: item.id,
productName: item.name,
price: item.price,
})
}
/>
</View>
)}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
},
title: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 16,
},
product: {
padding: 12,
marginBottom: 12,
borderWidth: 1,
borderColor: '#CCCCCC',
borderRadius: 8,
},
});
14.2 Create the Product Details Screen
// screens/ProductDetailsScreen.js
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default function ProductDetailsScreen({ route }) {
const {
productId,
productName,
price,
} = route.params ?? {};
return (
<View style={styles.container}>
<Text style={styles.title}>Product Details</Text>
<Text>Product ID: {productId ?? 'Unavailable'}</Text>
<Text>Product Name: {productName ?? 'Unknown Product'}</Text>
<Text>Price: {price != null ? `₹${price}` : 'Unavailable'}</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
padding: 20,
},
title: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 16,
},
});
14.3 Configure the Stack Navigator
// App.js
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import ProductListScreen from './screens/ProductListScreen';
import ProductDetailsScreen from './screens/ProductDetailsScreen';
const Stack = createNativeStackNavigator();
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="ProductList"
component={ProductListScreen}
options={{ title: 'Products' }}
/>
<Stack.Screen
name="ProductDetails"
component={ProductDetailsScreen}
options={{ title: 'Product Details' }}
/>
</Stack.Navigator>
</NavigationContainer>
);
}
14.4 Expected Result
The application displays a list of products. When the user selects View Details, the application opens the Product Details screen and displays the ID, name, and price passed from the list.
This example passes a few small values for learning purposes. In production, passing the product ID and retrieving the latest product data from an API or cache is often a better approach.
15. Best Practices for Passing Parameters
- Pass only necessary information: Avoid sending unnecessary data between screens.
- Prefer identifiers: Pass a product ID or user ID and retrieve the full record from an API or shared cache.
- Use consistent parameter names: Ensure that the source and destination screens use matching names.
- Handle missing values: Use optional chaining, defaults, and validation where appropriate.
- Keep parameters serializable: Prefer strings, numbers, booleans, arrays, and plain objects that can be serialized.
- Avoid passing functions: Functions and complex non-serializable values can interfere with navigation state persistence and deep linking.
- Do not use params as global state: Use an appropriate state-management solution or data cache for information shared across multiple screens.
- Protect sensitive information: Do not pass passwords, authentication secrets, or unnecessary personal information through navigation parameters.
- Validate incoming data: Parameters may be missing or malformed, especially when routes can be opened through deep links.
- Use appropriate navigation methods: Choose between navigate, push, and other methods according to the navigator and workflow.
- Test multiple scenarios: Check navigation with valid, missing, and unexpected parameter values.
16. Common Mistakes and Troubleshooting
| Problem |
Possible Cause |
Solution |
| Parameter is undefined |
The parameter was not passed or its name does not match. |
Check the object passed to the navigation method and the key read by the destination screen. |
| Cannot read property of undefined |
The code assumes route parameters always exist. |
Use optional chaining and validate required values. |
| Destination screen does not open |
The route is not registered or the route name is incorrect. |
Verify the navigator configuration and route names. |
| Wrong product details appear |
The source screen passes incorrect data or the destination uses stale data. |
Verify the selected item and retrieve the latest record using its ID when appropriate. |
| Nested screen does not receive parameters |
The nested navigation structure is configured incorrectly. |
Pass the parent route, nested screen name, and nested parameters using the correct structure. |
| Screen parameter does not update |
The wrong route is being updated or the component is not reading the updated parameter. |
Check the active route, the setParams call, and how the component uses route.params. |
| Navigation state persistence warning |
A non-serializable value such as a function was passed in the params. |
Pass serializable data and keep callbacks or complex application state elsewhere. |
| Invalid value causes a screen error |
Incoming parameters are not validated. |
Validate required IDs and display a fallback or error state. |
16.1 Debugging Checklist
- Confirm that the destination route is registered.
- Verify that the route name is spelled correctly.
- Inspect the parameters passed to the navigation method.
- Confirm that the destination screen reads the correct keys.
- Check whether parameters can be absent.
- Use temporary logging to inspect values during development.
- Check the nested navigator hierarchy if the destination is inside another navigator.
- Remove functions and other unnecessary non-serializable values from route parameters.
17. Passing Parameters with TypeScript
TypeScript can help developers define which parameters a screen expects. It improves editor assistance and catches many mistakes during development.
17.1 Define the Route Parameter List
export type RootStackParamList = {
Home: undefined;
Details: {
productId: string;
productName: string;
price: number;
};
};
The Home route does not require parameters, while Details expects a product ID, product name, and price.
17.2 Create a Typed Stack Navigator
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import type { RootStackParamList } from './types';
const Stack = createNativeStackNavigator<RootStackParamList>();
17.3 Type the Details Screen
import type { NativeStackScreenProps } from '@react-navigation/native-stack';
import type { RootStackParamList } from './types';
type DetailsScreenProps =
NativeStackScreenProps<RootStackParamList, 'Details'>;
export default function DetailsScreen({
route,
}: DetailsScreenProps) {
const { productId, productName, price } = route.params;
return (
<View>
<Text>{productId}</Text>
<Text>{productName}</Text>
<Text>₹{price}</Text>
</View>
);
}
With a typed route list, TypeScript can identify missing required parameters and many incorrectly named values. Keep the route types synchronized with the actual navigator configuration.
18. Navigation Parameters and Application State
Navigation parameters and application state serve different purposes. Understanding the difference helps prevent duplicated data and difficult-to-maintain applications.
| Navigation Parameters |
Application State |
| Identify or configure a destination screen. |
Store and manage application data and UI state. |
| Examples include item IDs, filters, sorting options, and page numbers. |
Examples include a shared cart, authenticated user state, and cached records. |
| Belong to the route's navigation state. |
May be managed by React state, Context, Redux, Zustand, or a data cache. |
| Should generally remain small and serializable. |
Can represent more complex application-specific data structures. |
For example, pass productId to the Product Details screen and retrieve the product from an API or cache. If the shopping cart must be shared across many screens, manage it through an appropriate shared state solution rather than repeatedly passing the entire cart through navigation.
19. Practice Exercises
- Create Home and Details screens and pass a username between them.
- Pass a numeric product ID from a product list to a details screen.
- Pass a product name, price, and category using one parameter object.
- Display a fallback value when an optional parameter is missing.
- Configure initial parameters for a Details screen.
- Update a route parameter using
navigation.setParams().
- Open multiple Details screen instances using
navigation.push().
- Use
useRoute() to read parameters in a child component.
- Pass parameters to a screen inside a nested navigator.
- Create a form screen and return a new title to the previous screen.
- Define a typed route parameter list using TypeScript.
- Test the application with missing, valid, and invalid parameter values.
20. Interview Questions and Answers
Q1. What are navigation parameters in React Native?
Answer: Navigation parameters are values passed to a destination screen during navigation. They help the screen identify what content to display or which options to apply.
Q2. How do you pass parameters using React Navigation?
Answer: Pass an object as the second argument to a navigation method, such as navigation.navigate('Details', { productId: 101 }).
Q3. How can a screen receive parameters?
Answer: A screen can access parameters from its route.params object.
Q4. What is the purpose of route.params?
Answer: It contains the parameter values associated with the current route.
Q5. What is useRoute()?
Answer: It is a React Navigation hook that provides access to the current route object from a component within the appropriate navigation context.
Q6. Can multiple parameters be passed at once?
Answer: Yes. Multiple key-value pairs can be placed inside the same parameter object.
Q7. What is initialParams?
Answer: It configures default parameters for a screen when navigation does not provide overriding values.
Q8. What does navigation.setParams() do?
Answer: It updates the current route's parameters by merging the provided values with existing parameters.
Q9. What is the difference between navigate() and push()?
Answer: navigate() navigates to a route according to the navigator's behavior, while push() creates another route instance on a stack navigator.
Q10. How can missing parameters be handled?
Answer: Use optional chaining, default values, and validation to prevent errors when parameters are absent.
Q11. Can arrays and objects be passed as parameters?
Answer: Serializable arrays and plain objects can be passed, but it is usually better to keep parameters small and pass identifiers for larger records.
Q12. Why should parameters be serializable?
Answer: Serializable parameters support navigation state persistence and deep linking more reliably and help avoid non-serializable state warnings.
Q13. How can parameters be passed to nested screens?
Answer: Navigate to the parent route and specify the nested screen and its parameter object using the structure supported by the navigator.
Q14. How can data be returned to a previous screen?
Answer: Use an appropriate return-navigation pattern, such as a supported stack method that returns to the previous route with parameters, or use shared application state for more complex updates.
Q15. Why is passing a complete user object often discouraged?
Answer: It can duplicate data, become stale, increase route complexity, and complicate deep linking. Passing a user ID and retrieving the latest record is often more maintainable.
Q16. Can navigation parameters replace global state?
Answer: No. Parameters are intended to identify or configure a destination screen. Shared application data is better managed using suitable application state or a data cache.
Q17. How can TypeScript improve parameter handling?
Answer: Typed route parameter lists help identify incorrect parameter names, missing required values, and incompatible data types during development.
Q18. What causes a parameter to be undefined?
Answer: The source screen may not pass the value, the parameter name may be incorrect, or the destination route may have been opened without parameters.
Q19. Should passwords be passed as navigation parameters?
Answer: No. Sensitive information such as passwords and authentication secrets should not be placed in route parameters.
Q20. What are common uses of navigation parameters?
Answer: Common uses include passing record IDs, search queries, filter settings, sort order, pagination values, and small amounts of screen-specific input data.
21. Quick Revision Notes
- Use
navigation.navigate('Details', { id: 101 }) to navigate and pass parameters.
- Read parameters through
route.params.
- Use
useRoute() when a component needs access to the current route through navigation context.
- Use
initialParams to configure default route parameters.
- Use
navigation.setParams() to update route parameters.
- Use
navigation.push() to add another route instance to a stack navigator.
- Use the appropriate nested-navigation syntax for child screens.
- Handle missing values with optional chaining and validation.
- Prefer passing identifiers instead of large data objects.
- Keep navigation parameters serializable and avoid sensitive data.
- Use shared state or a cache for data that must be managed across multiple screens.
- Use TypeScript route types to improve reliability in larger applications.
22. Conclusion
Passing parameters between screens is a fundamental React Native navigation skill. It allows screens to exchange the information needed to display selected products, user profiles, search results, form inputs, and other screen-specific content.
React Navigation provides a straightforward approach: pass a parameter object through a navigation method and read the values from route.params in the destination screen. Additional tools such as initialParams, useRoute(), and navigation.setParams() support default values, route access, and parameter updates.
For reliable applications, keep route parameters small, validate incoming values, use consistent naming, and separate navigation data from shared application state. Practicing these techniques will help you build React Native applications with cleaner navigation flows and more maintainable screen components.
23. Additional Learning Resources