React Native Components and App Development Strategy
Project Management and the node_modules Folder
- The Node Package Manager (NPM) is responsible for ensuring that all necessary packages are present for a given project.
- The majority of these packages are stored in the
node_modules folder. - NPM determines which packages and specific versions are needed by referencing the
./package.json manifest file. - Beyond the primary packages, NPM ensures that all dependencies (the libraries those packages themselves depend on) are also installed.
- The folder typically includes packages required for development, which contributes significantly to the massive total number of files.
- Important Transfer Rule: When copying or submitting a project, you should NOT include the
node_modules folder before transferring or zipping the files. Similarly, for Expo projects, you can delete any .expo files as they are dynamically recreated during the build process. - Data Comparison Example:
- A completed project folder can reach approximately 268MB in size and contain over 26k files.
- Without the
node_modules folder or .expo build files, that same project is only 1.19MB and consists of just 31 files.
Using NPM to Manage and Install Projects
- Since
node_modules is not included in templates or during migration, you must use NPM to rebuild the folder. - The command to reinstall all libraries from the project root is
npm install. - This command is also used to install specific packages, such as React Native Elements:
npm install react-native-elements. - Executing these commands, especially when creating a project via Expo, may result in warnings or errors:
- Errors: These prevent the project from running and must be addressed immediately.
- Warnings: These can often be ignored or corrected later, particularly if they are classified as low or moderate severity.
npm audit: This command provides details regarding specific errors and security vulnerabilities.npm audit fix [--force]: This command attempts to automatically resolve errors. - Caution: It is recommended to manually review and note errors before using this fix. The
--force switch should be used with extreme caution as it frequently introduces breaking changes.
Fundamentals of React Components
- React components (including those in React Native) are discrete containers that combine presentation (UI) with functionality.
- A screen view in a React Native app is typically a component, often composed of multiple sub-components.
- Component Hierarchy:
- Root Component: Every screen must have exactly one root component. This is typically a
View for single-page applications or a Navigation Container for multi-page applications. - Parent/Child: Components can be built to contain other components.
- Siblings: Developers can instantiate multiple autonomous instances of the same component side-by-side.
- Component Definitions:
- Function Components: Created as a function that returns JSX.
- Class Components: Created as a class containing a
render() method that returns JSX.
Function Components
- Function components are generally simpler and involve:
- Creating a function that accepts a single parameter for passed properties, known as "props."
- The "props" parameter can be a single value or an object containing multiple values.
- The function must include one or more
return statements that return a React element or JSX.
- Historical Context and State:
- Originally, functional components were stateless; once added to the virtual DOM, they maintained an unchanging state and were excluded from the lifecycle.
- In 2019, the addition of hooks allowed functional components to become stateful and tap into the component lifecycle.
- Scope: Utility functions or variables (like styles) defined within the component file are only visible within the scope of that document and are not visible to parent components.
Class Components
- Component classes are defined by extending the
React.Component class. - Members: They can contain properties (data) and methods (functions).
- Required Member: Every class component must have a
render() method to draw the component UI. - Constructor Method: A constructor is only necessary if you are initializing state or binding methods.
- If a constructor is defined, it must include a call to
super(props) to allow the use of the this keyword to access class members.
- State Management: Class components are inherently stateful and maintain a persistent state.
setState(): This method is used to alter the state, which triggers the component to re-render. - While
setState() cannot be called from outside the component, internal event handlers invoked by users or code can trigger it.
- Encapsulation: Classes can have private and public members to manage scope.
The React Component Lifecycle
- The lifecycle consists of three distinct phases:
- Mounting: Occurs when the component is first added to the User Interface (UI).
- Updating: Occurs when code changes a prop, when state is altered, or when an update is programmatically forced.
- Unmounting: Occurs when the component is destroyed or removed from the UI.
- Lifecycle Methods and Overrides:
- Developers can override specific methods to inject custom processes at key points.
render(): Functionally an override used to define the UI.componentDidMount(): Often overridden to load data immediately after the component has finished mounting.
- Functional Component Alternative: Functional components use hooks such as
useEffect() to handle lifecycle events, which fires on the first render and subsequent updates for specific state variables. - Lifecycle Phases (React version ≥16.4):
- Render Phase: Pure, no side effects; can be paused/restarted. Includes
constructor, getDerivedStateFromProps, shouldComponentUpdate, and render. - Pre-commit Phase: Can read the DOM. Includes
getSnapshotBeforeUpdate. - Commit Phase: Works with DOM, runs side effects, and schedules updates. Includes
componentDidMount, componentDidUpdate, and componentWillUnmount.
Props and State
- Properties (Props):
- Data passed as arguments when a component is created, similar to HTML attributes.
- In function components, these are received as a function parameter.
- In class components, they are passed during construction or added as attributes in JSX.
- Props are immutable and should remain unchanging.
- State:
- A collection of data that exists locally within a component.
- State should never be set directly. Instead, use
setState() (class) or a state hook (function) to trigger the update phase and re-render.
- Key Distinction: Props are set upon instantiation and are unchanging; state may be initialized from props but can change over time, forcing a re-render when it does.
Comparison: Class vs. Function Components
- Evolution: Prior to version 16.8 in 2019, stateful components required classes. Since then, hooks allow function components to be stateful.
- Recommendation: The React team generally recommends a functional approach because functions are more concise, easier to learn, and address requirements more directly.
- Benefits of Functions:
- More concise code.
- Avoids the need for complex service providers to attach reusable behaviors.
- Benefits of Classes:
- Direct access to
setState and lifecycle phases. - Support for inheritance (sub-classes).
- Support for access modifiers like
public, private, and protected in TypeScript. - Ability to encapsulate complex functionality (though this can lead to overly complex components).
TypeScript (TS) in React Development
- TypeScript is a Microsoft-created superset of JavaScript that acts as a pre-processor (similar to how SASS works for CSS).
- Code is written in TS and then transcompiled into standard JS.
- Key Features:
- Strict data typing (declared datatypes for variables).
- Object-oriented features: inheritance, interfaces, and structured class declarations.
- Advanced features: namespaces and enumerators.
- Advantages: Transcompilation identifies errors that vanilla JS would miss until runtime, which is vital for complex development environments.
React Native Core Components
- Basic Components:
View, Text, Image, TextInput, ScrollView, and StyleSheet. - User Interface:
Button and Switch. - List Views:
FlatList and SectionList. - Platform Specific (Android):
ToastAndroid, DrawerLayoutAndroid, PermissionsAndroid, and BackHandler. - Platform Specific (iOS):
ActionSheetIOS.
- Both are containers for holding multiple child components.
- View: Will not naturally expand beyond the viewport height. It can contain other Views or ScrollViews.
- ScrollView: Typically placed inside a View to bind maximum height. It enables scrolling when content exceeds the boundary.
- Performance Caveat: ScrollView renders all children simultaneously. It is not recommended for large datasets; use
FlatList instead. - Constraint: Do not nest a ScrollView inside another ScrollView.
List Components: FlatList and SectionList
- Built on the logic of React's
.map() feature. - Required Props for FlatList:
data: The source array (static or from an API).keyExtractor: Defines a unique ID for each item. If omitted, React defaults to the index, though a logical ID is preferred.renderItem: A function that returns JSX for a specific list item.
- SectionList: Used when the data array contains objects with their own data arrays. Requires a
renderSection prop for section headings. - Virtualization: Both components use lazy loading, rendering only the items in the immediate viewport. They should not be nested within a ScrollView as it prevents correct viewport height calculation.
Text and Image Components
- Text Component:
- Supports nested Text for inline styling (e.g.,
<Text>Show <Text style={}>something</Text> else</Text>). - Whitespace is ignored, but escape sequences like
\t (tab) and \n (line return) can be used. - Newlines in JSX:
<Text> Line return {'\n'} here </Text> or via template literals with backticks. - Calculations: JSX expressions can inject code results into text, such as
<Text>the result is {5 + 6}</Text>. - Note: Text components behave like inline HTML and ignore flexbox block-level styles.
- Image Component:
- Remote Images: Defined via
source={{uri: 'https://image.path'}}. Additional properties exist for caching and request types. - Local Images: Defined via
source={require('./assets/file.png')}. - Static Path Rule: Local image paths must be static. You cannot construct paths via string concatenation or loops because the
require() method must be able to package the file during the build process.