Refactoring your HomeScreen for better readability, maintainability, and scalability is a great step toward ensuring a robust and dynamic Expo mobile app. Below are several strategies and code examples to help you achieve a more modular and dynamic structure:
-
Modularize Components:
- Separate Concerns: Break down the
HomeScreen into smaller, reusable components.
- Create Custom Hooks: Encapsulate logic related to state management and business logic.
- Use Context or State Management Libraries: For managing global states like user data, goals, etc.
-
Optimize State Management:
- Combine Related States: Use objects or arrays to group related state variables.
- Memoize Components: Prevent unnecessary re-renders using
React.memo or useMemo.
-
Enhance Data Handling:
- Dynamic Data Sources: Fetch data from APIs or local storage instead of hardcoding.
- Use FlatList for Lists: Optimize rendering of list items like friends or exercises.
-
Improve Styling:
- Use StyleSheet.create: Optimize style creation and prevent inline styling where possible.
- Theming: Continue using theming but consider extracting theme-related logic.
-
Accessibility and Performance:
- Accessibility Props: Ensure all interactive elements have proper accessibility labels.
- Performance Optimization: Lazy load components or use virtualization for large lists.
Below is a refactored version of your HomeScreen.js implementing these strategies:
1. Create Separate Components
a. CarouselCard Component
Create a separate component for the carousel cards to make HomeScreen cleaner.
// Components/CarouselCard.js
import React from 'react';
import { View, Text } from 'react-native';
import { Button } from 'react-native-paper';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import createStyles from './CarouselCardStyles'; // Separate styles
const CarouselCard = ({ title, iconName, buttonTitle, onPress, children }) => {
const styles = createStyles();
return (
<View style={styles.card}>
<Icon name={iconName} size={30} color="#000" />
<Text style={styles.title}>{title}</Text>
<View style={styles.content}>{children}</View>
{buttonTitle && onPress && (
<Button
mode="contained"
onPress={onPress}
style={styles.button}
accessibilityLabel={`Navigate to ${buttonTitle}`}
accessibilityRole="button"
>
{buttonTitle}
</Button>
)}
</View>
);
};
export default React.memo(CarouselCard);
b. Tracker Components
For each tracker (Calories, Steps, Water), create separate components. Here's an example for the Calories Tracker:
// Components/CaloriesTracker.js
import React from 'react';
import { View, Text, Alert } from 'react-native';
import { ProgressBar, Button } from 'react-native-paper';
import createStyles from './CaloriesTrackerStyles';
const CaloriesTracker = ({ calories, goal, onAdd, onReset, theme }) => {
const styles = createStyles(theme);
const remaining = goal - calories;
const handleAdd = () => {
if (calories + 100 <= goal) {
onAdd(100);
} else {
Alert.alert('Great Job!', 'You have reached your daily calorie goal!');
}
};
return (
<View>
<Text style={styles.text}>Consumed: {calories} kcal</Text>
<ProgressBar progress={calories / goal} color={theme.colors.primary} style={styles.progressBar} />
<Text style={styles.text}>Remaining: {remaining} kcal</Text>
<View style={styles.buttonContainer}>
<Button
mode="contained"
onPress={handleAdd}
icon="plus"
style={styles.button}
accessibilityLabel="Add 100 kcal"
accessibilityRole="button"
>
Add 100 kcal
</Button>
<Button
mode="outlined"
onPress={onReset}
icon="refresh"
style={styles.button}
accessibilityLabel="Reset calories"
accessibilityRole="button"
>
Reset
</Button>
</View>
</View>
);
};
export default React.memo(CaloriesTracker);
2. Create Custom Hooks
a. useCalorieTracker Hook
// hooks/useCalorieTracker.js
import { useState } from 'react';
const useCalorieTracker = (initial = 1500, goal = 2000) => {
const [calories, setCalories] = useState(initial);
const addCalories = (amount) => {
setCalories((prev) => Math.min(prev + amount, goal));
};
const resetCalories = () => setCalories(0);
return { calories, goal, addCalories, resetCalories };
};
export default useCalorieTracker;
b. Repeat Similar Hooks for Steps and Water
3. Refactor HomeScreen
// frontend/screens/Home/HomeScreen.js
import React, { useContext, useState, useMemo } from 'react';
import { View, Text, SafeAreaView, ScrollView, Dimensions, Alert, StyleSheet } from 'react-native';
import { AuthContext } from '../../context/AuthContext';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { useTheme, ProgressBar, Button, Card } from 'react-native-paper';
import Carousel from 'react-native-reanimated-carousel';
import CarouselCard from '../../Components/CarouselCard';
import CaloriesTracker from '../../Components/CaloriesTracker';
import StepsTracker from '../../Components/StepsTracker';
import WaterTracker from '../../Components/WaterTracker';
import MacroNutrients from '../../Components/MacroNutrients';
import ExerciseTracker from '../../Components/ExerciseTracker';
import FriendsOverview from '../../Components/FriendsOverview';
import NavigationButtons from '../../Components/NavigationButtons';
import useCalorieTracker from '../../hooks/useCalorieTracker';
import useStepsTracker from '../../hooks/useStepsTracker';
import useWaterTracker from '../../hooks/useWaterTracker';
import { useNavigation } from '@react-navigation/native';
import createStyles from './HomeScreenStyles';
const { width: screenWidth } = Dimensions.get('window');
const HomeScreen = () => {
const { user } = useContext(AuthContext);
const theme = useTheme();
const navigation = useNavigation();
const styles = createStyles(theme); // Generate styles based on the theme
// Custom Hooks for trackers
const {
calories,
goal: calorieGoal,
addCalories,
resetCalories,
} = useCalorieTracker();
const {
steps,
goal: stepGoal,
addSteps,
resetSteps,
} = useStepsTracker();
const {
waterIntake,
waterGoal,
addWater,
resetWater,
} = useWaterTracker();
// State for exercises and friends can also be managed via hooks or context if needed
const [exercises, setExercises] = useState([
{ id: '1', name: 'Push Ups', duration: '30 mins' },
{ id: '2', name: 'Running', duration: '45 mins' },
]);
const [friends, setFriends] = useState([
{ id: '1', name: 'Alice', progress: 60 },
{ id: '2', name: 'Bob', progress: 80 },
]);
// State for Carousel Pagination
const [activeSlide, setActiveSlide] = useState(0);
// Define Carousel Items using useMemo for performance
const carouselItems = useMemo(() => [
{
title: 'Calorie Tracker',
iconName: 'fire',
content: (
<CaloriesTracker
calories={calories}
goal={calorieGoal}
onAdd={addCalories}
onReset={resetCalories}
theme={theme}
/>
),
buttonTitle: 'Add Food',
onPress: () => navigation.navigate('Nutrition'),
},
{
title: 'Macro Nutrients',
iconName: 'food',
content: <MacroNutrients />,
buttonTitle: null,
onPress: null,
},
{
title: 'Steps Tracker',
iconName: 'walk',
content: (
<StepsTracker
steps={steps}
goal={stepGoal}
onAdd={addSteps}
onReset={resetSteps}
theme={theme}
/>
),
buttonTitle: 'View Steps',
onPress: () => navigation.navigate('Steps'),
},
{
title: 'Exercise Tracker',
iconName: 'dumbbell',
content: (
<ExerciseTracker
exercises={exercises}
onAddExercise={(exercise) => setExercises([...exercises, exercise])}
navigation={navigation}
/>
),
buttonTitle: 'Add Exercise',
onPress: () => navigation.navigate('Exercises'),
},
{
title: 'Water Tracker',
iconName: 'cup-water',
content: (
<WaterTracker
waterIntake={waterIntake}
waterGoal={waterGoal}
onAdd={addWater}
onReset={resetWater}
theme={theme}
/>
),
buttonTitle: null,
onPress: null,
},
], [calories, calorieGoal, addCalories, resetCalories, steps, stepGoal, addSteps, resetSteps, exercises, waterIntake, waterGoal, addWater, resetWater, navigation, theme]);
const renderCarouselItem = ({ item }) => (
<CarouselCard
title={item.title}
iconName={item.iconName}
buttonTitle={item.buttonTitle}
onPress={item.onPress}
>
{item.content}
</CarouselCard>
);
return (
<SafeAreaView style={styles.safeArea}>
<ScrollView contentContainerStyle={styles.container}>
{/* Welcome Message */}
<Text style={styles.title}>
{user ? `Welcome, ${user.name}!` : 'Welcome!'}
</Text>
{/* Carousel Section */}
<View style={styles.carouselContainer}>
<Carousel
width={screenWidth * 0.9} // Width of the carousel
height={350} // Reduced height from 400 to 350
data={carouselItems}
scrollAnimationDuration={300} // Adjusted for smooth transitions
onSnapToItem={(index) => setActiveSlide(index)}
renderItem={renderCarouselItem}
mode="parallax" // Carousel mode
modeConfig={{
parallaxScrollingScale: 0.9,
parallaxScrollingOffset: 50,
}}
loop
autoPlay={false}
/>
{/* Custom Pagination */}
<View style={styles.paginationContainer}>
{carouselItems.map((_, index) => (
<View
key={index}
style={[
styles.paginationDot,
activeSlide === index && styles.activePaginationDot,
]}
/>
))}
</View>
</View>
{/* Friends Overview Card */}
<FriendsOverview friends={friends} navigation={navigation} theme={theme} />
{/* Navigation Buttons */}
<NavigationButtons navigation={navigation} theme={theme} />
</ScrollView>
</SafeAreaView>
);
};
export default HomeScreen;
4. Create Additional Components
a. FriendsOverview Component
// Components/FriendsOverview.js
import React from 'react';
import { View, Text } from 'react-native';
import { ProgressBar, Card, Button } from 'react-native-paper';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import createStyles from './FriendsOverviewStyles';
const FriendsOverview = ({ friends, navigation, theme }) => {
const styles = createStyles(theme);
return (
<Card style={styles.card}>
<Card.Title
title="Friends"
titleStyle={styles.title}
left={(props) => <Icon {...props} name="account-group" size={30} color={theme.colors.primary} />}
/>
<Card.Content>
{friends.map((friend) => (
<View key={friend.id} style={styles.friendItem}>
<Text style={styles.friendName}>{friend.name}</Text>
<ProgressBar
progress={friend.progress / 100}
color={theme.colors.primary}
style={styles.progressBar}
/>
<Text style={styles.progressText}>Progress: {friend.progress}%</Text>
</View>
))}
</Card.Content>
<Card.Actions style={styles.actions}>
<Button
onPress={() => navigation.navigate('Friends')}
mode="contained"
icon="account-group"
style={styles.button}
contentStyle={styles.buttonContent}
accessibilityLabel="View friends progress"
accessibilityRole="button"
>
View Friends
</Button>
</Card.Actions>
</Card>
);
};
export default React.memo(FriendsOverview);
b. NavigationButtons Component
// Components/NavigationButtons.js
import React from 'react';
import { View } from 'react-native';
import { Button } from 'react-native-paper';
import createStyles from './NavigationButtonsStyles';
const NavigationButtons = ({ navigation, theme }) => {
const styles = createStyles(theme);
const buttons = [
{ title: 'Resources', icon: 'book-open-page-variant', screen: 'Resources' },
{ title: 'Calculator', icon: 'calculator', screen: 'Calculator' },
{ title: 'Connect', icon: 'link', screen: 'Connect' },
{ title: 'Community', icon: 'account-supervisor', screen: 'Community' },
{ title: 'Exercises', icon: 'dumbbell', screen: 'Exercises' },
];
return (
<View style={styles.container}>
{buttons.map((btn) => (
<Button
key={btn.title}
mode="contained"
icon={btn.icon}
onPress={() => navigation.navigate(btn.screen)}
style={styles.button}
contentStyle={styles.buttonContent}
accessibilityLabel={`Navigate to ${btn.title}`}
accessibilityRole="button"
>
{btn.title}
</Button>
))}
</View>
);
};
export default React.memo(NavigationButtons);
5. Create Custom Hooks for Other Trackers
a. useStepsTracker Hook
// hooks/useStepsTracker.js
import { useState } from 'react';
const useStepsTracker = (initial = 7500, goal = 10000) => {
const [steps, setSteps] = useState(initial);
const addSteps = (amount) => {
setSteps((prev) => Math.min(prev + amount, goal));
};
const resetSteps = () => setSteps(0);
return { steps, goal, addSteps, resetSteps };
};
export default useStepsTracker;
b. useWaterTracker Hook
// hooks/useWaterTracker.js
import { useState } from 'react';
const useWaterTracker = (initial = 0, goal = 8) => {
const [waterIntake, setWaterIntake] = useState(initial);
const addWater = () => {
if (waterIntake < goal) {
setWaterIntake(waterIntake + 1);
} else {
Alert.alert('Great Job!', 'You have reached your daily water intake goal!');
}
};
const resetWater = () => setWaterIntake(0);
return { waterIntake, waterGoal: goal, addWater, resetWater };
};
export default useWaterTracker;
6. Optimize Styles
Use StyleSheet.create to define styles in separate files to improve performance and maintainability.
Example: HomeScreenStyles.js
// frontend/screens/Home/HomeScreenStyles.js
import { StyleSheet } from 'react-native';
const createStyles = (theme) => StyleSheet.create({
safeArea: {
flex: 1,
backgroundColor: theme.colors.background,
},
container: {
padding: 16,
alignItems: 'center',
},
title: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 16,
color: theme.colors.text,
},
carouselContainer: {
marginBottom: 24,
},
paginationContainer: {
flexDirection: 'row',
alignSelf: 'center',
marginTop: 8,
},
paginationDot: {
width: 8,
height: 8,
borderRadius: 4,
backgroundColor: theme.colors.disabled,
margin: 4,
},
activePaginationDot: {
backgroundColor: theme.colors.primary,
},
card: {
width: '100%',
marginBottom: 16,
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
},
actionButton: {
marginVertical: 8,
width: '100%',
},
buttonContent: {
flexDirection: 'row-reverse',
},
});
export default createStyles;
7. Use FlatList for Friends and Exercises
Optimizing rendering lists with FlatList improves performance, especially with larger datasets.
Example: FriendsOverview Component with FlatList
// Components/FriendsOverview.js
import React from 'react';
import { View, Text, FlatList } from 'react-native';
import { ProgressBar, Card, Button } from 'react-native-paper';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import createStyles from './FriendsOverviewStyles';
const FriendsOverview = ({ friends, navigation, theme }) => {
const styles = createStyles(theme);
const renderFriend = ({ item }) => (
<View style={styles.friendItem}>
<Text style={styles.friendName}>{item.name}</Text>
<ProgressBar
progress={item.progress / 100}
color={theme.colors.primary}
style={styles.progressBar}
/>
<Text style={styles.progressText}>Progress: {item.progress}%</Text>
</View>
);
return (
<Card style={styles.card}>
<Card.Title
title="Friends"
titleStyle={styles.title}
left={(props) => <Icon {...props} name="account-group" size={30} color={theme.colors.primary} />}
/>
<Card.Content>
<FlatList
data={friends}
renderItem={renderFriend}
keyExtractor={(item) => item.id}
contentContainerStyle={styles.list}
/>
</Card.Content>
<Card.Actions style={styles.actions}>
<Button
onPress={() => navigation.navigate('Friends')}
mode="contained"
icon="account-group"
style={styles.button}
contentStyle={styles.buttonContent}
accessibilityLabel="View friends progress"
accessibilityRole="button"
>
View Friends
</Button>
</Card.Actions>
</Card>
);
};
export default React.memo(FriendsOverview);
8. Enhance Accessibility
Ensure all interactive elements have appropriate accessibilityLabel and accessibilityRole props to improve the app's accessibility.
9. Leverage Memoization
Use React.memo for components and useMemo or useCallback for functions to prevent unnecessary re-renders.
10. Dynamic Data Handling
Replace hardcoded data with dynamic data fetched from APIs or other data sources. Use useEffect hooks to fetch data when components mount.
Example: Fetching Friends Data
// hooks/useFriends.js
import { useState, useEffect } from 'react';
import axios from 'axios'; // Or any other data fetching library
const useFriends = () => {
const [friends, setFriends] = useState([]);
useEffect(() => {
const fetchFriends = async () => {
try {
const response = await axios.get('/api/friends'); // Replace with your API endpoint
setFriends(response.data);
} catch (error) {
console.error('Failed to fetch friends:', error);
}
};
fetchFriends();
}, []);
return friends;
};
export default useFriends;
Usage in FriendsOverview Component
// frontend/screens/Home/HomeScreen.js
import useFriends from '../../hooks/useFriends';
// Inside HomeScreen component
const friends = useFriends();
11. Implement Global State Management (Optional)
For larger applications, consider using state management libraries like Redux or Zustand to manage global states more efficiently.
12. Final Directory Structure
Organizing your project directory enhances maintainability. Here's a suggested structure:
/frontend
/components
/CarouselCard.js
/CaloriesTracker.js
/StepsTracker.js
/WaterTracker.js
/MacroNutrients.js
/ExerciseTracker.js
/FriendsOverview.js
/NavigationButtons.js
/...other components
/styles
/CarouselCardStyles.js
/CaloriesTrackerStyles.js
/FriendsOverviewStyles.js
/NavigationButtonsStyles.js
/...other styles
/hooks
/useCalorieTracker.js
/useStepsTracker.js
/useWaterTracker.js
/useFriends.js
/...other hooks
/screens
/Home
/HomeScreen.js
/HomeScreenStyles.js
/...other screens
/context
/AuthContext.js
/...other contexts
/navigation
/index.js
/...other navigation files
/assets
/...images, fonts, etc.
/...other directories
13. Benefits of Refactoring
- Readability: Clear separation of components and concerns makes the code easier to read and understand.
- Reusability: Smaller components can be reused across different parts of the app.
- Maintainability: Easier to manage and update individual components without affecting others.
- Performance: Optimized rendering and state management improve app performance.
- Scalability: A modular structure can accommodate future features and enhancements seamlessly.
14. Conclusion
By breaking down your HomeScreen into smaller, focused components and utilizing custom hooks, you create a scalable and maintainable codebase. This approach not only enhances the developer experience but also improves the app's performance and responsiveness.
Note: Remember to create corresponding style files for each component (e.g., CaloriesTrackerStyles.js, FriendsOverviewStyles.js) using StyleSheet.create to maintain consistency and optimize performance.