App Architecture & Best Practices

8 min read

⚛️ React Native: App Architecture & Best Practices

Welcome, aspiring React Native artisan! You've learned the basics, you can build components, but now you're wondering... how do I build an app that doesn't collapse under its own weight? How do I write code that my future self (and my teammates) will thank me for?

This guide is your treasure map to building robust, scalable, and maintainable React Native applications. We'll explore the architectural patterns and best practices that separate the weekend hobbyist from the seasoned professional.

📂 Structuring Your Project Folders Effectively

The Problem: You start a new project, and everything is in the root directory. App.js, your components, your images... it's a digital junk drawer. As your app grows, finding anything becomes a nightmare.

The Solution: A well-organized folder structure. Think of it like organizing your kitchen. You wouldn't throw your spoons, forks, and knives into one big pile, would you? (If you do, we need to have a separate conversation).

A logical folder structure makes your codebase easier to navigate, understand, and maintain.

A Scalable Folder Structure

Here's a widely-used, feature-first structure that scales well for most projects:

jboss-cli
/src
  /assets
    /images
    /fonts
  /components
    /common
      /Button.js
      /Card.js
    /featureA
      /Header.js
  /features
    /Authentication
      /components
      /screens
        /LoginScreen.js
        /SignupScreen.js
      /services
      /utils
    /Profile
      /components
      /screens
        /ProfileScreen.js
      /services
  /navigation
    /AppNavigator.js
  /services
    /api.js
  /store
    /authSlice.js
  /utils
    /helpers.js
  /hooks
    /useFetch.js
  /config
    /theme.js

Breakdown of Key Folders:

  • src: This is where all your source code lives. It keeps your app's logic separate from configuration files.
  • assets: Static files like images, fonts, and icons go here.
  • components: This folder is for your reusable UI components.
    • common: Houses highly reusable, generic components like buttons, inputs, and modals.
    • featureA: Contains components specific to a particular feature.
  • features: This is the heart of the feature-first approach. Each feature of your app gets its own folder, containing everything related to it.
  • navigation: All your React Navigation setup, including stack navigators and tab navigators, resides here.
  • services: For your API calls and other external service integrations.
  • store: If you're using a state management library like Redux or Zustand, your store, reducers, and actions live here.
  • utils: A place for helper functions and constants that are used across the application.
  • hooks: Your custom React hooks that encapsulate reusable logic.
  • config: For theme definitions, environment variables, and other global configurations.

✨ Interesting Fact: The "feature-first" (or "domain-driven") approach to folder structure is a battle-tested pattern that helps keep your codebase modular and easy to scale. It's like having a dedicated toolbox for each type of repair job – everything you need is right there.

🎨 Creating Highly Reusable UI Components

The Problem: You find yourself copying and pasting the same button style or card layout across multiple screens. When you need to make a small change, you have to hunt down every instance and update it. 🤦‍♂️

The Solution: Build a library of reusable UI components. These are the fundamental building blocks of your application's user interface.

What Makes a Component "Reusable"?

A truly reusable component is:

  • Generic: It doesn't contain any business logic specific to one feature.
  • Customizable: You can change its appearance and behavior through props.
  • Self-contained: All its styles and logic are encapsulated within the component itself.

Example: A Reusable Button Component

Let's create a Button component that we can use throughout our app.

javascript
// src/components/common/Button.js
import React from 'react';
import { TouchableOpacity, Text, StyleSheet } from 'react-native';

const Button = ({ title, onPress, style, textStyle }) => {
  return (
    <TouchableOpacity style={[styles.button, style]} onPress={onPress}>
      <Text style={[styles.text, textStyle]}>{title}</Text>
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  button: {
    backgroundColor: '#007AFF',
    paddingVertical: 12,
    paddingHorizontal: 24,
    borderRadius: 8,
    alignItems: 'center',
    justifyContent: 'center',
  },
  text: {
    color: '#FFFFFF',
    fontSize: 16,
    fontWeight: 'bold',
  },
});

export default Button;

How to Use It:

javascript
import React from 'react';
import { View } from 'react-native';
import Button from '../components/common/Button';

const MyScreen = () => {
  return (
    <View>
      {/* Default button */}
      <Button title="Press Me" onPress={() => alert('Button pressed!')} />

      {/* Customized button */}
      <Button
        title="Warning"
        onPress={() => alert('Warning!')}
        style={{ backgroundColor: 'red', marginTop: 10 }}
        textStyle={{ color: 'white' }}
      />
    </View>
  );
};

export default MyScreen;

By creating this simple Button component, we've established a consistent look and feel for buttons across our app. If we need to change the default button color, we only need to update it in one place!

🎣 Writing Custom Hooks for Clean Logic

The Problem: You have component logic, like fetching data from an API or handling form state, that you need to use in multiple components. Copying and pasting this logic leads to code duplication and makes your components bloated.

The Solution: Extract that logic into a custom hook. Custom hooks are JavaScript functions that start with use and can call other hooks. They allow you to reuse stateful logic without changing your component hierarchy.

Why Use Custom Hooks?

  • DRY (Don't Repeat Yourself): Encapsulate and reuse logic across your app.
  • Cleaner Components: Separate your UI from your business logic, making your components easier to read and maintain.
  • Improved Testability: You can test your custom hooks in isolation.

Example: A Custom Hook for Fetching Data (useFetch)

A very common task in mobile apps is fetching data from an API. Let's create a useFetch hook to handle this.

javascript
// src/hooks/useFetch.js
import { useState, useEffect } from 'react';
import axios from 'axios';

const useFetch = (url) => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get(url);
        setData(response.data);
      } catch (err) {
        setError(err);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [url]);

  return { data, loading, error };
};

export default useFetch;

How to Use It:

javascript
import React from 'react';
import { View, Text, ActivityIndicator, FlatList } from 'react-native';
import useFetch from '../hooks/useFetch';

const PostList = () => {
  const { data: posts, loading, error } = useFetch('https://jsonplaceholder.typicode.com/posts');

  if (loading) {
    return <ActivityIndicator size="large" />;
  }

  if (error) {
    return <Text>Error fetching posts: {error.message}</Text>;
  }

  return (
    <View>
      <FlatList
        data={posts}
        keyExtractor={(item) => item.id.toString()}
        renderItem={({ item }) => (
          <View style={{ padding: 10, borderBottomWidth: 1, borderBottomColor: '#ccc' }}>
            <Text style={{ fontWeight: 'bold' }}>{item.title}</Text>
            <Text>{item.body}</Text>
          </View>
        )}
      />
    </View>
  );
};

export default PostList;

Look at how clean our PostList component is! All the complex logic for fetching data is neatly tucked away in our useFetch hook.

🚧 Error Boundaries: Preventing Total App Crashes

The Problem: A JavaScript error in a part of your UI tree causes the entire app to crash, leaving your users staring at a dreaded white screen. 😱

The Solution: Use Error Boundaries. Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.

How Do They Work?

An error boundary is a class component that defines one or both of the following lifecycle methods:

  • static getDerivedStateFromError(error): This is used to render a fallback UI after an error has been thrown.
  • componentDidCatch(error, errorInfo): This is used to log error information.

Important Note: Error boundaries do not catch errors for:

  • Event handlers (use a try...catch block)
  • Asynchronous code (like setTimeout or requestAnimationFrame callbacks)
  • Server-side rendering
  • Errors thrown in the error boundary itself

Example: A Simple Error Boundary

javascript
// src/components/common/ErrorBoundary.js
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';

class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // You can also log the error to an error reporting service
    console.log('Uncaught error:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return (
        <View style={styles.container}>
          <Text style={styles.title}>Oops, something went wrong.</Text>
          <Text style={styles.message}>We're working on fixing it. Please restart the app.</Text>
        </View>
      );
    }

    return this.props.children;
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold',
    marginBottom: 10,
  },
  message: {
    fontSize: 16,
    textAlign: 'center',
  },
});

export default ErrorBoundary;

How to Use It:

You can wrap any part of your component tree with an ErrorBoundary. A common practice is to wrap your entire app or individual navigation screens.

javascript
// App.js
import React from 'react';
import ErrorBoundary from './src/components/common/ErrorBoundary';
import AppNavigator from './src/navigation/AppNavigator';

const App = () => {
  return (
    <ErrorBoundary>
      <AppNavigator />
    </ErrorBoundary>
  );
};

export default App;

Now, if an error occurs within AppNavigator, your users will see a friendly message instead of a crash.


And there you have it! By applying these principles of solid app architecture and best practices, you're well on your way to building React Native applications that are not only functional but also a joy to work on. Happy coding! 🚀

📚 Additional Resources

Challenge

You are tasked with building a small React application that demonstrates several advanced architectural patterns: custom hooks for logic reuse, reusable components, and error boundaries for graceful error handling.

Your Tasks:

  1. Create a Custom Hook useAPI:

    • This hook must accept a url string as its only argument.
    • It should manage three internal states: data (initially null), loading (initially true), and error (initially null).
    • Use a useEffect hook to simulate a network request with a setTimeout of 1 second.
    • If the url prop is 'success', update the state to loading: false, error: null, and data: { message: 'Data fetched successfully!' }.
    • If the url prop is 'error', update the state to loading: false, error: { message: 'Failed to fetch data' }, and data: null.
    • The hook must return an object: { data, loading, error }.
  2. Create an ErrorBoundary Class Component:

    • This component must be a class component that extends React.Component.
    • Implement static getDerivedStateFromError(error) to update state and trigger a fallback UI.
    • Implement componentDidCatch(error, errorInfo) to log the error information (a console.log is sufficient).
    • If an error is caught, it should render a fallback UI: <div>Something went wrong.</div>.
    • Otherwise, it should render this.props.children.
  3. Create a Reusable DataDisplay Component:

    • This component will accept a url prop.
    • It should call your useAPI hook, passing the url prop to it.
    • If the hook's loading state is true, render <div>Loading...</div>.
    • If the hook's error state is not null, you must throw a new Error with the error message from the hook. This is crucial for the ErrorBoundary to catch it.
    • If the hook provides data, render the message inside a div: <div>{data.message}</div>.
  4. Update the App Component:

    • Wrap both <DataDisplay /> instances inside your ErrorBoundary component.

Expected result

Your final code should contain a complete and correct implementation for useAPI, ErrorBoundary, DataDisplay, and the modified App component.

  • useAPI: The custom hook correctly uses useState and useEffect to manage and return { data, loading, error } states after a simulated 1-second delay, based on the input url.
  • ErrorBoundary: The class component correctly implements static getDerivedStateFromError and componentDidCatch. It has a state property (e.g., hasError) to conditionally render its children or a fallback UI.
  • DataDisplay: The component correctly calls the useAPI hook. It renders a 'Loading...' message initially. Crucially, it must throw new Error() when the hook returns an error object, which allows the ErrorBoundary to catch it. On success, it displays the data message.
  • App: The main component must wrap the two DataDisplay instances within the <ErrorBoundary> tags. Because the second <DataDisplay url="error" /> instance will throw an error, the ErrorBoundary will activate and display its fallback UI instead of rendering any of its children.
jsx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.