InterviewPitch
React Native interview questions

React Native Interview Questions with Answers

Most Asked React Native Interview Questions for Mobile Developer Roles

100+ QuestionsDetailed AnswersCode ExamplesUpdated for 2026

Introduction

React Native is a powerful open-source framework developed by Meta that allows developers to build cross-platform mobile applications using JavaScript and React. With React Native, you can create truly native iOS and Android apps from a single codebase, sharing up to 90% of the code across platforms. This eliminates the need for separate Swift/Objective-C and Java/Kotlin teams, drastically reducing development time and costs. This comprehensive guide brings you 100+ carefully curated React Native interview questions and answers, covering everything from the fundamentals to advanced mobile development topics. You'll master components, JSX, props, state, hooks (useState, useEffect, useContext, useReducer), custom hooks, navigation (Stack, Tab, Drawer), FlatList and SectionList for efficient lists, API integration with fetch/axios, AsyncStorage for local persistence, animations with Animated API, gestures, push notifications, permissions, debugging, performance optimization, and real-world mobile development patterns. Whether you're preparing for a mobile developer role, a React Native specialist position, or a full-stack job that includes mobile, this question bank will solidify your understanding and give you the confidence to ace your interview. Start practicing now and become a React Native expert.

Why React Native?

  • Cross-platform development – write once, run on both iOS and Android
  • Reuses React knowledge – leverage existing frontend skills for mobile
  • Native performance – uses real native components and APIs
  • Hot reloading – rapid development with instant feedback
  • Vast ecosystem – extensive libraries and community support
  • Backed by Meta – used in production apps like Facebook, Instagram, and Shopify
  • High demand in the job market – one of the top cross-platform frameworks

Most Asked React Native Interview Questions

Beginner
1. What is React Native?

React Native is an open-source framework for building mobile applications using JavaScript and React. It allows you to create native mobile apps for iOS and Android using a single codebase.

  • Cross-platform: Write once, run on iOS and Android
  • Native components: Uses real native UI components
  • React-based: Uses React's component-based architecture
  • Fast refresh: Instant reloading during development
  • Large ecosystem: Extensive third-party libraries
typescript
// Hello World in React Native
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';

const App = () => {
  return (
    <View style={styles.container}>
      <Text style={styles.text}>Hello, World!</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    fontSize: 20,
    color: 'black',
  },
});

export default App;
Beginner
2. How to declare variables in React Native?

Variables in React Native are declared using JavaScript's var, let, or const. State variables are managed using useState.

  • let: Mutable variable
  • const: Constant variable
  • useState: State variable that triggers re-renders
  • Props: Immutable variables passed from parent
  • Context: Global variables accessible throughout the app
typescript
// Variables in React Native
import React, { useState } from 'react';
import { View, Text, Button } from 'react-native';

const App = () => {
  // State variables
  const [mutableVar, setMutableVar] = useState('Hello');
  const [count, setCount] = useState(0);
  
  // Constants
  const API_URL = 'https://api.example.com';
  
  // Regular variables (re-renders won't update UI)
  let regularVar = 'World';
  
  return (
    <View>
      <Text>{mutableVar}</Text>
      <Text>Count: {count}</Text>
      <Button 
        title="Update" 
        onPress={() => {
          setMutableVar('Updated');
          setCount(count + 1);
        }}
      />
    </View>
  );
};
Beginner
3. What are the data types in React Native?

React Native uses JavaScript data types including primitives, objects, arrays, and special React Native types.

  • Primitive: string, number, boolean, null, undefined
  • Object: Plain objects, arrays, functions
  • React Native specific: JSX elements, components
  • Style types: StyleSheet, ViewStyle, TextStyle, ImageStyle
  • Event types: SyntheticEvent, NativeSyntheticEvent
typescript
// Data Types in React Native
import React from 'react';
import { View, Text } from 'react-native';

const DataTypesExample = () => {
  // String
  const str = 'Hello React Native';
  
  // Number
  const intNum = 10;
  const floatNum = 3.14;
  
  // Boolean
  const isActive = true;
  
  // Array
  const arr = [1, 2, 3, 4, 5];
  
  // Object
  const person = {
    name: 'Alice',
    age: 25,
    city: 'NYC'
  };
  
  // Null and Undefined
  const nullValue = null;
  const undefinedValue = undefined;
  
  return (
    <View>
      <Text>String: {str}</Text>
      <Text>Number: {intNum}</Text>
      <Text>Boolean: {isActive ? 'Active' : 'Inactive'}</Text>
      <Text>Array: {arr.join(', ')}</Text>
      <Text>Object: {person.name}</Text>
    </View>
  );
};

export default DataTypesExample;
Beginner
4. How to define functions in React Native?

Functions in React Native are defined using JavaScript function declarations or arrow functions, with hooks for state and effects.

  • Arrow functions: const add = (a, b) => a + b
  • Function declarations: function add(a, b) { return a + b }
  • Component functions: const App = () => { return <View />; }
  • Event handlers: const handlePress = () => { }
  • Custom hooks: const useCustomHook = () => { }
typescript
// Functions in React Native
import React from 'react';
import { View, Text, Button } from 'react-native';

// Regular function
function add(a, b) {
  return a + b;
}

// Arrow function
const subtract = (a, b) => a - b;

// Function with default parameters
const greet = (name = 'Guest') => `Hello, ${name}!`;

// Function component
const App = () => {
  // Function with multiple return values
  const divide = (a, b) => ({
    quotient: Math.floor(a / b),
    remainder: a % b
  });
  
  // Higher-order function
  const operate = (a, b, operation) => operation(a, b);
  
  // Lambda function
  const multiply = (a, b) => a * b;
  
  const result = divide(10, 3);
  
  return (
    <View>
      <Text>Add: {add(5, 3)}</Text>
      <Text>Subtract: {subtract(10, 4)}</Text>
      <Text>Greet: {greet('Alice')}</Text>
      <Text>Quotient: {result.quotient}</Text>
      <Text>Remainder: {result.remainder}</Text>
      <Text>Multiply: {operate(6, 7, multiply)}</Text>
    </View>
  );
};

export default App;
Beginner
5. What are arrays in React Native?

Arrays in React Native are JavaScript arrays used for storing lists of data, often rendered using FlatList or mapped to JSX elements.

  • Creation: const numbers = [1, 2, 3, 4, 5]
  • State arrays: const [items, setItems] = useState([])
  • Rendering: FlatList, map()
  • Methods: push, pop, filter, map, reduce
  • Immutability: setItems([...items, newItem])
typescript
// Arrays in React Native
import React, { useState } from 'react';
import { View, Text, Button, FlatList } from 'react-native';

const App = () => {
  // Array creation
  const [numbers, setNumbers] = useState([1, 2, 3, 4, 5]);
  const strings = ['Apple', 'Banana', 'Orange'];
  
  // Array operations
  const addNumber = () => {
    setNumbers([...numbers, numbers.length + 1]);
  };
  
  const removeNumber = () => {
    setNumbers(numbers.slice(0, -1));
  };
  
  // Array methods
  const doubled = numbers.map(x => x * 2);
  const filtered = numbers.filter(x => x > 2);
  const sum = numbers.reduce((a, b) => a + b, 0);
  
  return (
    <View>
      <Text>Numbers: {numbers.join(', ')}</Text>
      <Text>Doubled: {doubled.join(', ')}</Text>
      <Text>Filtered: {filtered.join(', ')}</Text>
      <Text>Sum: {sum}</Text>
      <Button title="Add Number" onPress={addNumber} />
      <Button title="Remove Number" onPress={removeNumber} />
      
      <FlatList
        data={strings}
        renderItem={({item}) => <Text>{item}</Text>}
        keyExtractor={(item, index) => index.toString()}
      />
    </View>
  );
};

export default App;
Beginner
6. What are collections in React Native?

React Native uses JavaScript collections like Arrays, Objects, Sets, and Maps for storing and managing data.

  • Arrays: Ordered lists of items
  • Objects: Key-value pairs for structured data
  • Sets: Unique values collection
  • Maps: Key-value pairs with any key type
  • Immutable patterns: Spread operator, Object.assign
typescript
// Collections in React Native
import React, { useState } from 'react';
import { View, Text, FlatList } from 'react-native';

const App = () => {
  // Array (List)
  const [list, setList] = useState([1, 2, 3, 4, 5]);
  
  // Object (Map/Dictionary)
  const user = {
    name: 'Alice',
    age: 25,
    city: 'NYC'
  };
  
  // Array of objects
  const users = [
    { id: 1, name: 'Alice', age: 25 },
    { id: 2, name: 'Bob', age: 30 },
    { id: 3, name: 'Charlie', age: 35 }
  ];
  
  // Set (using array with unique values)
  const uniqueValues = [...new Set([1, 2, 2, 3, 3, 4])];
  
  // Map (using object)
  const userMap = {
    'user1': { name: 'Alice', age: 25 },
    'user2': { name: 'Bob', age: 30 }
  };
  
  // Collection operations
  const evens = list.filter(x => x % 2 === 0);
  const doubled = list.map(x => x * 2);
  const sum = list.reduce((a, b) => a + b, 0);
  
  return (
    <View>
      <Text>List: {list.join(', ')}</Text>
      <Text>User: {user.name}, {user.age}</Text>
      <Text>Unique: {uniqueValues.join(', ')}</Text>
      
      <FlatList
        data={users}
        renderItem={({item}) => (
          <Text>{item.name} ({item.age})</Text>
        )}
        keyExtractor={(item) => item.id.toString()}
      />
    </View>
  );
};

export default App;
Beginner
7. What are components in React Native?

Components are the building blocks of React Native applications. They can be functional or class-based and return JSX elements.

  • Functional components: const MyComponent = () => { return <View />; }
  • Class components: class MyComponent extends React.Component
  • Props: Input data passed to components
  • State: Internal data managed with hooks
  • Lifecycle: useEffect for managing side effects
typescript
// Components as Data Classes in React Native
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';

// Functional component as data class
const Person = ({ name, age, city = 'Unknown' }) => {
  return (
    <View style={styles.personContainer}>
      <Text style={styles.name}>Name: {name}</Text>
      <Text style={styles.age}>Age: {age}</Text>
      <Text style={styles.city}>City: {city}</Text>
    </View>
  );
};

// Class component as data class
class PersonClass extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: props.name || 'Unknown',
      age: props.age || 0,
      city: props.city || 'Unknown'
    };
  }
  
  render() {
    return (
      <View style={styles.personContainer}>
        <Text style={styles.name}>Name: {this.state.name}</Text>
        <Text style={styles.age}>Age: {this.state.age}</Text>
        <Text style={styles.city}>City: {this.state.city}</Text>
      </View>
    );
  }
}

const App = () => {
  return (
    <View style={styles.container}>
      <Person name="Alice" age={25} city="NYC" />
      <PersonClass name="Bob" age={30} city="LA" />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
  },
  personContainer: {
    padding: 10,
    marginBottom: 10,
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 5,
  },
  name: { fontSize: 18, fontWeight: 'bold' },
  age: { fontSize: 16 },
  city: { fontSize: 16 },
});

export default App;
Beginner
8. What is prop validation in React Native?

Prop validation ensures components receive the correct props types. It can be done using PropTypes or TypeScript.

  • PropTypes: Runtime type checking
  • TypeScript: Compile-time type checking
  • Required props: prop.isRequired
  • Default props: Component.defaultProps =
  • Custom validators: Custom prop validation functions
typescript
// PropTypes and Type Checking in React Native
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import PropTypes from 'prop-types';

const User = ({ name, age, email, status, hobbies }) => {
  return (
    <View style={styles.container}>
      <Text style={styles.name}>Name: {name}</Text>
      <Text style={styles.text}>Age: {age}</Text>
      <Text style={styles.text}>Email: {email}</Text>
      <Text style={styles.text}>Status: {status}</Text>
      <Text style={styles.text}>Hobbies: {hobbies.join(', ')}</Text>
    </View>
  );
};

// PropTypes for type checking
User.propTypes = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number.isRequired,
  email: PropTypes.string,
  status: PropTypes.oneOf(['active', 'inactive', 'pending']),
  hobbies: PropTypes.arrayOf(PropTypes.string)
};

// Default props
User.defaultProps = {
  email: 'No email provided',
  status: 'active',
  hobbies: []
};

// Using TypeScript interface (TypeScript)
interface UserProps {
  name: string;
  age: number;
  email?: string;
  status?: 'active' | 'inactive' | 'pending';
  hobbies?: string[];
}

const UserTS: React.FC<UserProps> = ({ name, age, email = 'No email', status = 'active', hobbies = [] }) => {
  return (
    <View>
      <Text>{name}</Text>
      <Text>{age}</Text>
    </View>
  );
};

const App = () => {
  return (
    <View>
      <User name="Alice" age={25} status="active" hobbies={['reading', 'gaming']} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: { padding: 10, margin: 10, borderWidth: 1, borderRadius: 5 },
  name: { fontSize: 18, fontWeight: 'bold' },
  text: { fontSize: 16 }
});

export default App;
Beginner
9. What is null safety in React Native?

React Native uses JavaScript's null and undefined handling with optional chaining and conditional rendering for safety.

  • Optional chaining: user?.name
  • Nullish coalescing: value ?? 'default'
  • Conditional rendering: {data && <Text>{data}</Text>}
  • Default values: const name = user?.name || 'Guest'
  • TypeScript: Strict null checking
typescript
// Null Safety in React Native
import React, { useState } from 'react';
import { View, Text, TextInput, Button } from 'react-native';

const App = () => {
  const [nullableString, setNullableString] = useState(null);
  const [nonNullableString, setNonNullableString] = useState('Hello');
  
  // Safe access with optional chaining
  const displayString = nullableString?.toUpperCase() || 'Default';
  
  // Null check with conditional rendering
  const renderContent = () => {
    if (nullableString) {
      return <Text>String is: {nullableString}</Text>;
    } else {
      return <Text>String is null</Text>;
    }
  };
  
  // Elvis operator equivalent
  const elvis = (value, defaultValue) => value || defaultValue;
  
  // Safe navigation with optional chaining
  const user = {
    name: 'Alice',
    address: {
      city: 'NYC'
    }
  };
  
  const city = user?.address?.city || 'Unknown';
  
  return (
    <View>
      <Text>Nullable: {displayString}</Text>
      <Text>City: {city}</Text>
      {renderContent()}
      
      <TextInput
        placeholder="Enter text"
        onChangeText={setNullableString}
        value={nullableString || ''}
      />
      
      <Button
        title="Set to null"
        onPress={() => setNullableString(null)}
      />
    </View>
  );
};

export default App;
Beginner
10. How to do conditional rendering in React Native?

Conditional rendering in React Native is done using if statements, ternary operators, logical AND (&&), or switch statements.

  • If-else: if (condition) { return <View />; }
  • Ternary: {condition ? <View /> : <Text />}
  • Logical AND: {condition && <View />}
  • Switch: switch (status) { case 'loading': ... }
  • Immediately invoked: {(() => { if (condition) return <View />; })()}
typescript
// Conditional Rendering in React Native
import React, { useState } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';

const App = () => {
  const [age, setAge] = useState(25);
  const [isLoggedIn, setIsLoggedIn] = useState(true);
  const [status, setStatus] = useState('loading');
  
  // If-else in render
  const renderStatus = () => {
    if (age < 18) {
      return <Text style={styles.minor}>Minor</Text>;
    } else if (age < 65) {
      return <Text style={styles.adult}>Adult</Text>;
    } else {
      return <Text style={styles.senior}>Senior</Text>;
    }
  };
  
  // Ternary operator
  const loginStatus = isLoggedIn ? 'Logged In' : 'Logged Out';
  
  // Logical AND (&&)
  const showAdmin = isLoggedIn && age >= 18 && <Text>Admin Panel</Text>;
  
  // Switch statement
  const renderSwitch = () => {
    switch(status) {
      case 'loading':
        return <Text>Loading...</Text>;
      case 'success':
        return <Text>Success!</Text>;
      case 'error':
        return <Text>Error occurred</Text>;
      default:
        return null;
    }
  };
  
  return (
    <View style={styles.container}>
      <Text>Age: {age}</Text>
      {renderStatus()}
      <Text>Status: {loginStatus}</Text>
      {showAdmin}
      {renderSwitch()}
      
      <Button title="Increment Age" onPress={() => setAge(age + 1)} />
      <Button title="Toggle Login" onPress={() => setIsLoggedIn(!isLoggedIn)} />
      <Button title="Toggle Status" onPress={() => {
        const states = ['loading', 'success', 'error'];
        const currentIndex = states.indexOf(status);
        setStatus(states[(currentIndex + 1) % states.length]);
      }} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20 },
  minor: { color: 'orange', fontSize: 18 },
  adult: { color: 'green', fontSize: 18 },
  senior: { color: 'red', fontSize: 18 }
});

export default App;
Beginner
11. What are props in React Native?

Props (properties) are read-only inputs passed to components. They allow parent components to pass data to child components.

  • Passing props: <Component name="Alice" />
  • Receiving props: const Component = ({ name }) => {}
  • Default props: Component.defaultProps = {}
  • Children: props.children
  • Immutable: Props cannot be modified by child
typescript
// Components and Props in React Native
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';

// Base component
const Animal = ({ name, sound = 'Animal sound' }) => {
  return (
    <View style={styles.animalContainer}>
      <Text style={styles.name}>{name}</Text>
      <Text style={styles.sound}>Sound: {sound}</Text>
    </View>
  );
};

// Derived component (composition)
const Dog = ({ name, breed }) => {
  return (
    <View style={styles.dogContainer}>
      <Animal name={name} sound="Woof!" />
      <Text style={styles.breed}>Breed: {breed}</Text>
    </View>
  );
};

// Component with children
const Card = ({ children, title }) => {
  return (
    <View style={styles.card}>
      <Text style={styles.cardTitle}>{title}</Text>
      {children}
    </View>
  );
};

// Higher-Order Component (HOC)
const withLogger = (WrappedComponent) => {
  return (props) => {
    console.log('Rendering component with props:', props);
    return <WrappedComponent {...props} />;
  };
};

const LoggedAnimal = withLogger(Animal);

// Render Props pattern
const DataProvider = ({ render }) => {
  const data = { name: 'Alice', age: 25 };
  return render(data);
};

const App = () => {
  return (
    <View style={styles.container}>
      <Card title="Animal Info">
        <Animal name="Rex" sound="Woof!" />
      </Card>
      
      <Dog name="Rex" breed="German Shepherd" />
      
      <LoggedAnimal name="Whiskers" sound="Meow!" />
      
      <DataProvider render={(data) => (
        <Text>{data.name} is {data.age} years old</Text>
      )} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20 },
  animalContainer: { padding: 10, marginBottom: 5, borderWidth: 1 },
  dogContainer: { padding: 10, marginBottom: 5, borderWidth: 1, borderColor: 'blue' },
  card: { padding: 15, marginBottom: 10, borderWidth: 1, borderRadius: 5 },
  cardTitle: { fontSize: 18, fontWeight: 'bold', marginBottom: 10 },
  name: { fontSize: 16, fontWeight: 'bold' },
  sound: { fontSize: 14 },
  breed: { fontSize: 14, color: 'blue' }
});

export default App;
Beginner
12. What is state in React Native?

State is internal data that can change over time and triggers re-renders when updated. It's managed using the useState hook.

  • useState: const [state, setState] = useState(initial)
  • Immutable updates: setState({ ...state, newKey: value })
  • Functional updates: setState(prev => prev + 1)
  • Lazy initialization: useState(() => expensiveComputation())
  • State lifting: Moving state to parent component
typescript
// State Management in React Native
import React, { useState, useReducer } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';

// useState example
const Counter = () => {
  const [count, setCount] = useState(0);
  const [name, setName] = useState('');
  
  return (
    <View style={styles.container}>
      <Text>Count: {count}</Text>
      <Button title="Increment" onPress={() => setCount(count + 1)} />
      <Button title="Decrement" onPress={() => setCount(count - 1)} />
      <Button title="Reset" onPress={() => setCount(0)} />
    </View>
  );
};

// useReducer example
const initialState = { count: 0 };
const reducer = (state, action) => {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    case 'reset':
      return { count: 0 };
    default:
      return state;
  }
};

const ReducerCounter = () => {
  const [state, dispatch] = useReducer(reducer, initialState);
  
  return (
    <View style={styles.container}>
      <Text>Count: {state.count}</Text>
      <Button title="Increment" onPress={() => dispatch({ type: 'increment' })} />
      <Button title="Decrement" onPress={() => dispatch({ type: 'decrement' })} />
      <Button title="Reset" onPress={() => dispatch({ type: 'reset' })} />
    </View>
  );
};

// useState with object
const UserForm = () => {
  const [user, setUser] = useState({ name: '', age: '' });
  
  const updateUser = (field, value) => {
    setUser({ ...user, [field]: value });
  };
  
  return (
    <View>
      <Text>Name: {user.name}</Text>
      <Text>Age: {user.age}</Text>
      <Button title="Update Name" onPress={() => updateUser('name', 'Alice')} />
      <Button title="Update Age" onPress={() => updateUser('age', '25')} />
    </View>
  );
};

const App = () => {
  return (
    <View style={styles.appContainer}>
      <Counter />
      <ReducerCounter />
      <UserForm />
    </View>
  );
};

const styles = StyleSheet.create({
  appContainer: { flex: 1, padding: 20 },
  container: { marginBottom: 20, padding: 10, borderWidth: 1 }
});

export default App;
Intermediate
13. What are custom hooks in React Native?

Custom hooks are reusable functions that encapsulate stateful logic. They allow sharing logic between components.

  • Naming: Must start with use
  • Composition: Can use other hooks inside
  • Reusable: Share logic across components
  • Cleaner code: Extract complex logic from components
  • Testing: Easier to test isolated logic
typescript
// Custom Hooks in React Native
import React, { useState, useEffect } from 'react';
import { View, Text, Button } from 'react-native';

// Custom hook for counter
const useCounter = (initialValue = 0) => {
  const [count, setCount] = useState(initialValue);
  
  const increment = () => setCount(count + 1);
  const decrement = () => setCount(count - 1);
  const reset = () => setCount(initialValue);
  
  return { count, increment, decrement, reset };
};

// Custom hook for toggle
const useToggle = (initialValue = false) => {
  const [value, setValue] = useState(initialValue);
  const toggle = () => setValue(!value);
  return [value, toggle];
};

// Custom hook with side effects
const useWindowSize = () => {
  const [size, setSize] = useState({ width: 0, height: 0 });
  
  useEffect(() => {
    const updateSize = () => {
      setSize({
        width: window.innerWidth,
        height: window.innerHeight
      });
    };
    
    window.addEventListener('resize', updateSize);
    updateSize();
    
    return () => window.removeEventListener('resize', updateSize);
  }, []);
  
  return size;
};

// Custom hook for API calls
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 fetch(url);
        const json = await response.json();
        setData(json);
        setLoading(false);
      } catch (err) {
        setError(err);
        setLoading(false);
      }
    };
    
    fetchData();
  }, [url]);
  
  return { data, loading, error };
};

// Using custom hooks
const App = () => {
  const { count, increment, decrement, reset } = useCounter(10);
  const [isOn, toggle] = useToggle(false);
  
  return (
    <View>
      <Text>Count: {count}</Text>
      <Button title="Increment" onPress={increment} />
      <Button title="Decrement" onPress={decrement} />
      <Button title="Reset" onPress={reset} />
      <Text>Toggle: {isOn ? 'ON' : 'OFF'}</Text>
      <Button title="Toggle" onPress={toggle} />
    </View>
  );
};

export default App;
Intermediate
14. How to handle errors in React Native?

Error handling in React Native uses try-catch blocks, Error Boundaries, and Alert dialogs to manage and display errors.

  • Try-catch: Handle synchronous errors
  • Async/await: Catch errors in async operations
  • Error Boundaries: Catch component errors
  • Alert: Display errors to users
  • Logging: Console.error for debugging
typescript
// Error Handling in React Native
import React, { useState } from 'react';
import { View, Text, Button, Alert } from 'react-native';

// Try-catch in component
const SafeComponent = () => {
  const [error, setError] = useState(null);
  
  const riskyOperation = () => {
    try {
      // Simulate error
      throw new Error('Something went wrong');
    } catch (err) {
      setError(err.message);
      Alert.alert('Error', err.message);
    }
  };
  
  return (
    <View>
      {error && <Text style={{color: 'red'}}>Error: {error}</Text>}
      <Button title="Risky Operation" onPress={riskyOperation} />
    </View>
  );
};

// Error Boundary
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }

  componentDidCatch(error, errorInfo) {
    console.log('Error caught:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <View>
          <Text style={{color: 'red', fontSize: 18}}>Something went wrong</Text>
          <Text>{this.state.error?.message}</Text>
          <Button 
            title="Reset" 
            onPress={() => this.setState({ hasError: false, error: null })}
          />
        </View>
      );
    }

    return this.props.children;
  }
}

// Async error handling
const AsyncComponent = () => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  
  const fetchData = async () => {
    try {
      setLoading(true);
      const response = await fetch('https://api.example.com/data');
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      const json = await response.json();
      setData(json);
      setError(null);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };
  
  return (
    <View>
      {loading && <Text>Loading...</Text>}
      {error && <Text style={{color: 'red'}}>Error: {error}</Text>}
      {data && <Text>Data loaded</Text>}
      <Button title="Fetch Data" onPress={fetchData} />
    </View>
  );
};

const App = () => {
  return (
    <View style={{flex: 1, padding: 20}}>
      <ErrorBoundary>
        <SafeComponent />
        <AsyncComponent />
      </ErrorBoundary>
    </View>
  );
};

export default App;
Intermediate
15. What are arrow functions in React Native?

Arrow functions are a concise way to write functions in JavaScript. They are commonly used for event handlers and callbacks in React Native.

  • Syntax: const fn = () => { }
  • Lexical this: Inherits this from parent scope
  • Implicit return: const add = (a, b) => a + b
  • Event handlers: onPress={() => handlePress()}
  • Higher-order: const double = (x) => x * 2
typescript
// Arrow Functions in React Native
import React from 'react';
import { View, Text, Button } from 'react-native';

// Basic arrow function
const square = (x) => x * x;

// Arrow function with multiple parameters
const add = (a, b) => a + b;

// Arrow function with multiple lines
const multiply = (a, b) => {
  const result = a * b;
  return result;
};

// Higher-order function
const operate = (a, b, operation) => operation(a, b);

// Returning arrow function
const getMultiplier = (factor) => {
  return (x) => x * factor;
};

// Arrow function in component
const App = () => {
  // Arrow function as event handler
  const handlePress = () => {
    console.log('Button pressed');
  };
  
  // Arrow function with parameters
  const handlePressWithParam = (value) => {
    console.log('Value:', value);
  };
  
  // Arrow function in render
  const renderItem = (item) => (
    <Text key={item.id}>{item.name}</Text>
  );
  
  const double = getMultiplier(2);
  const result = operate(10, 20, (a, b) => a + b);
  
  return (
    <View>
      <Text>Square of 5: {square(5)}</Text>
      <Text>Add: {add(5, 3)}</Text>
      <Text>Multiply: {multiply(5, 3)}</Text>
      <Text>Double of 5: {double(5)}</Text>
      <Text>Result: {result}</Text>
      
      <Button title="Press Me" onPress={handlePress} />
      <Button 
        title="Press with Param" 
        onPress={() => handlePressWithParam('Hello')}
      />
    </View>
  );
};

export default App;
Intermediate
16. What is useEffect in React Native?

useEffect is a hook that handles side effects in functional components. It runs after render and can clean up on unmount.

  • Basic: useEffect(() => { }, [])
  • Dependencies: Controls when effect runs
  • Cleanup: Return function for cleanup
  • Data fetching: API calls and async operations
  • Subscriptions: Event listeners, timers
typescript
// useEffect and Lifecycle in React Native
import React, { useState, useEffect } from 'react';
import { View, Text, Button } from 'react-native';

const App = () => {
  const [count, setCount] = useState(0);
  const [data, setData] = useState(null);
  
  // ComponentDidMount (runs once)
  useEffect(() => {
    console.log('Component mounted');
    
    // Cleanup (ComponentWillUnmount)
    return () => {
      console.log('Component unmounted');
    };
  }, []);
  
  // ComponentDidUpdate (runs when count changes)
  useEffect(() => {
    console.log('Count updated to:', count);
  }, [count]);
  
  // ComponentDidUpdate (runs on any update)
  useEffect(() => {
    console.log('Component updated');
  });
  
  // Fetch data on mount
  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch('https://api.example.com/data');
      const json = await response.json();
      setData(json);
    };
    
    fetchData();
  }, []);
  
  // Timer effect
  useEffect(() => {
    const interval = setInterval(() => {
      console.log('Tick');
    }, 1000);
    
    return () => clearInterval(interval);
  }, []);
  
  // Effect with dependencies
  const [userId, setUserId] = useState(1);
  
  useEffect(() => {
    console.log('User ID changed to:', userId);
    // Fetch user data when userId changes
  }, [userId]);
  
  return (
    <View>
      <Text>Count: {count}</Text>
      <Button title="Increment" onPress={() => setCount(count + 1)} />
      <Button title="Change User" onPress={() => setUserId(userId + 1)} />
      {data && <Text>Data loaded</Text>}
    </View>
  );
};

export default App;
Intermediate
17. What are custom hooks and reusability?

Custom hooks allow extracting and reusing stateful logic across components. They improve code organization and reusability.

  • Encapsulation: Encapsulate complex logic
  • Reuse: Share logic between components
  • Cleaner code: Reduce component complexity
  • Testing: Easier to unit test
  • Composition: Combine multiple hooks
typescript
// Custom Hooks and Reusability in React Native
import React, { useState, useEffect, useRef } from 'react';
import { View, Text, Button, TextInput } from 'react-native';

// Custom hook for form handling
const useForm = (initialValues) => {
  const [values, setValues] = useState(initialValues);
  const [errors, setErrors] = useState({});
  
  const handleChange = (name, value) => {
    setValues({ ...values, [name]: value });
  };
  
  const validate = (validationRules) => {
    const newErrors = {};
    for (const field in validationRules) {
      const rule = validationRules[field];
      if (rule.required && !values[field]) {
        newErrors[field] = `${field} is required`;
      }
      if (rule.pattern && !rule.pattern.test(values[field])) {
        newErrors[field] = `${field} is invalid`;
      }
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  
  const reset = () => {
    setValues(initialValues);
    setErrors({});
  };
  
  return { values, errors, handleChange, validate, reset };
};

// Custom hook for debounce
const useDebounce = (value, delay) => {
  const [debouncedValue, setDebouncedValue] = useState(value);
  
  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);
    
    return () => clearTimeout(handler);
  }, [value, delay]);
  
  return debouncedValue;
};

// Custom hook for previous value
const usePrevious = (value) => {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  }, [value]);
  return ref.current;
};

// Custom hook for local storage
const useLocalStorage = (key, initialValue) => {
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      return initialValue;
    }
  });
  
  const setValue = (value) => {
    try {
      const valueToStore = value instanceof Function ? value(storedValue) : value;
      setStoredValue(valueToStore);
      localStorage.setItem(key, JSON.stringify(valueToStore));
    } catch (error) {
      console.log(error);
    }
  };
  
  return [storedValue, setValue];
};

// Using custom hooks
const App = () => {
  const form = useForm({ name: '', email: '' });
  const [search, setSearch] = useState('');
  const debouncedSearch = useDebounce(search, 500);
  const [count, setCount] = useState(0);
  const prevCount = usePrevious(count);
  
  return (
    <View>
      <TextInput
        placeholder="Name"
        value={form.values.name}
        onChangeText={(text) => form.handleChange('name', text)}
      />
      <TextInput
        placeholder="Email"
        value={form.values.email}
        onChangeText={(text) => form.handleChange('email', text)}
      />
      <Text>Search: {debouncedSearch}</Text>
      <Text>Count: {count}</Text>
      <Text>Previous Count: {prevCount}</Text>
      <Button title="Increment" onPress={() => setCount(count + 1)} />
    </View>
  );
};

export default App;
Intermediate
18. How to use TypeScript in React Native?

TypeScript adds static typing to React Native, improving code quality and developer experience with type checking and IntelliSense.

  • Type annotations: const name: string = 'Alice'
  • Interfaces: interface Props { name: string }
  • Generic components: <T>(props: Props<T>) => {}
  • Type inference: Automatically infer types
  • Strict mode: "strict": true in tsconfig
typescript
// TypeScript in React Native
import React from 'react';
import { View, Text, StyleSheet, FlatList } from 'react-native';

// Type definitions
type User = {
  id: number;
  name: string;
  age: number;
  email?: string;
};

type Status = 'active' | 'inactive' | 'pending';

interface UserProps {
  user: User;
  status?: Status;
  onPress?: (id: number) => void;
}

// Functional component with TypeScript
const UserCard: React.FC<UserProps> = ({ user, status = 'active', onPress }) => {
  return (
    <View style={styles.card}>
      <Text style={styles.name}>{user.name}</Text>
      <Text style={styles.text}>Age: {user.age}</Text>
      {user.email && <Text style={styles.text}>Email: {user.email}</Text>}
      <Text style={[styles.status, styles[status]]}>Status: {status}</Text>
    </View>
  );
};

// Generic component
const DataList = <T extends { id: number }>({ 
  data, 
  renderItem 
}: { 
  data: T[]; 
  renderItem: (item: T) => React.ReactNode;
}) => {
  return (
    <FlatList
      data={data}
      renderItem={({ item }) => renderItem(item)}
      keyExtractor={(item) => item.id.toString()}
    />
  );
};

// Custom hook with TypeScript
const useFetch = <T,>(url: string) => {
  const [data, setData] = React.useState<T | null>(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<Error | null>(null);
  
  React.useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const json = await response.json();
        setData(json);
        setLoading(false);
      } catch (err) {
        setError(err as Error);
        setLoading(false);
      }
    };
    
    fetchData();
  }, [url]);
  
  return { data, loading, error };
};

// App component
const App: React.FC = () => {
  const users: User[] = [
    { id: 1, name: 'Alice', age: 25, email: 'alice@example.com' },
    { id: 2, name: 'Bob', age: 30 },
    { id: 3, name: 'Charlie', age: 35 }
  ];
  
  return (
    <View style={styles.container}>
      <DataList
        data={users}
        renderItem={(item) => (
          <UserCard user={item} status="active" />
        )}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20 },
  card: { padding: 15, marginBottom: 10, borderWidth: 1, borderRadius: 5 },
  name: { fontSize: 18, fontWeight: 'bold' },
  text: { fontSize: 16 },
  status: { fontSize: 16, marginTop: 5 },
  active: { color: 'green' },
  inactive: { color: 'red' },
  pending: { color: 'orange' }
});

export default App;
Intermediate
19. What are Higher-Order Components in React Native?

Higher-Order Components (HOCs) are functions that take a component and return an enhanced component. They are used for cross-cutting concerns.

  • Definition: const withAuth = (Component) => (props) => { }
  • Enhancement: Add features to components
  • Composition: Chain multiple HOCs
  • Common uses: Authentication, logging, data fetching
  • Alternative: Custom hooks (preferred approach)
typescript
// Higher-Order Components (HOC) in React Native
import React from 'react';
import { View, Text, StyleSheet, ActivityIndicator } from 'react-native';

// HOC for logging
const withLogger = (WrappedComponent) => {
  return (props) => {
    console.log('Rendering component with props:', props);
    return <WrappedComponent {...props} />;
  };
};

// HOC for authentication
const withAuth = (WrappedComponent) => {
  return (props) => {
    const isAuthenticated = true; // Would come from context or state
    
    if (!isAuthenticated) {
      return (
        <View style={styles.authContainer}>
          <Text>Please login to continue</Text>
        </View>
      );
    }
    
    return <WrappedComponent {...props} />;
  };
};

// HOC for loading state
const withLoading = (WrappedComponent) => {
  return ({ isLoading, ...props }) => {
    if (isLoading) {
      return (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color="#0000ff" />
          <Text>Loading...</Text>
        </View>
      );
    }
    
    return <WrappedComponent {...props} />;
  };
};

// HOC for data fetching
const withData = (url) => (WrappedComponent) => {
  return (props) => {
    const [data, setData] = React.useState(null);
    const [loading, setLoading] = React.useState(true);
    const [error, setError] = React.useState(null);
    
    React.useEffect(() => {
      const fetchData = async () => {
        try {
          const response = await fetch(url);
          const json = await response.json();
          setData(json);
          setLoading(false);
        } catch (err) {
          setError(err);
          setLoading(false);
        }
      };
      
      fetchData();
    }, []);
    
    if (loading) {
      return (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" />
          <Text>Loading...</Text>
        </View>
      );
    }
    
    if (error) {
      return (
        <View style={styles.errorContainer}>
          <Text>Error loading data</Text>
        </View>
      );
    }
    
    return <WrappedComponent data={data} {...props} />;
  };
};

// HOC for style enhancement
const withStyles = (styles) => (WrappedComponent) => {
  return (props) => {
    return <WrappedComponent {...props} style={[props.style, styles]} />;
  };
};

// Base component
const UserProfile = ({ name, age, email, style }) => {
  return (
    <View style={[styles.profileContainer, style]}>
      <Text style={styles.profileName}>Name: {name}</Text>
      <Text style={styles.profileText}>Age: {age}</Text>
      <Text style={styles.profileText}>Email: {email}</Text>
    </View>
  );
};

// Enhanced components
const LoggedUserProfile = withLogger(UserProfile);
const AuthenticatedUserProfile = withAuth(UserProfile);
const LoadingUserProfile = withLoading(UserProfile);
const DataUserProfile = withData('https://api.example.com/user')(UserProfile);
const StyledUserProfile = withStyles({ backgroundColor: '#f0f0f0' })(UserProfile);

// Composing HOCs
const EnhancedUserProfile = withStyles({ backgroundColor: '#f0f0f0' })(
  withLogger(
    withLoading(
      withAuth(UserProfile)
    )
  )
);

// App
const App = () => {
  return (
    <View style={styles.appContainer}>
      <UserProfile name="Alice" age={25} email="alice@example.com" />
      <LoggedUserProfile name="Bob" age={30} email="bob@example.com" />
      <LoadingUserProfile isLoading={false} name="Charlie" age={35} email="charlie@example.com" />
    </View>
  );
};

const styles = StyleSheet.create({
  appContainer: { flex: 1, padding: 20 },
  authContainer: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  loadingContainer: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  errorContainer: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  profileContainer: { padding: 15, marginBottom: 10, borderWidth: 1, borderRadius: 5 },
  profileName: { fontSize: 18, fontWeight: 'bold' },
  profileText: { fontSize: 16 }
});

export default App;
Intermediate
20. What are higher-order functions in React Native?

Higher-order functions are functions that operate on other functions. They can accept functions as arguments or return functions.

  • Function arguments: const operate = (a, b, fn) => fn(a, b)
  • Returning functions: const getMultiplier = (x) => (y) => x * y
  • Composition: Combining functions
  • Array methods: map, filter, reduce
  • Debouncing: debounce(() => { }, 300)
typescript
// Higher-Order Functions in React Native
import React, { useState } from 'react';
import { View, Text, Button, FlatList } from 'react-native';

// Function that takes a function as parameter
const applyOperation = (a, b, operation) => operation(a, b);

// Function that returns a function
const getMultiplier = (factor) => {
  return (x) => x * factor;
};

// Function composition
const compose = (f, g) => {
  return (x) => f(g(x));
};

// Higher-order function with multiple lambdas
const processValue = (value, transform, filter) => {
  return filter(value) ? transform(value) : null;
};

// Array higher-order functions
const App = () => {
  const [numbers, setNumbers] = useState([1, 2, 3, 4, 5]);
  
  // Using higher-order functions
  const square = (x) => x * x;
  const addTen = (x) => x + 10;
  const isEven = (x) => x % 2 === 0;
  
  const double = getMultiplier(2);
  const squareThenAddTen = compose(addTen, square);
  
  const result = applyOperation(10, 20, (a, b) => a + b);
  const processed = processValue(5, square, isEven);
  
  // Array operations
  const doubled = numbers.map(double);
  const evens = numbers.filter(isEven);
  const sum = numbers.reduce((a, b) => a + b, 0);
  
  return (
    <View>
      <Text>Result: {result}</Text>
      <Text>Double of 5: {double(5)}</Text>
      <Text>Square then add ten: {squareThenAddTen(5)}</Text>
      <Text>Processed: {processed}</Text>
      <Text>Doubled: {doubled.join(', ')}</Text>
      <Text>Evens: {evens.join(', ')}</Text>
      <Text>Sum: {sum}</Text>
      
      <Button 
        title="Add Number" 
        onPress={() => setNumbers([...numbers, numbers.length + 1])}
      />
    </View>
  );
};

export default App;
Advanced
21. How to use async/await in React Native?

Async/await is used in React Native for handling asynchronous operations like API calls, database operations, and file system access.

  • async functions: const fetchData = async () => { }
  • await: Wait for promise resolution
  • Error handling: try { } catch (error) { }
  • Parallel requests: await Promise.all([...])
  • Timeout: Implement with AbortController
typescript
// Async/Await in React Native
import React, { useState } from 'react';
import { View, Text, Button, ActivityIndicator, FlatList } from 'react-native';

const App = () => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  
  // Basic async function
  const fetchData = async () => {
    try {
      setLoading(true);
      setError(null);
      
      // Simulate API call
      const response = await fetch('https://jsonplaceholder.typicode.com/users');
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      const json = await response.json();
      setData(json);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };
  
  // Async function with timeout
  const fetchWithTimeout = async (url, timeout) => {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), timeout);
    
    try {
      const response = await fetch(url, { signal: controller.signal });
      const json = await response.json();
      clearTimeout(timeoutId);
      return json;
    } catch (err) {
      clearTimeout(timeoutId);
      if (err.name === 'AbortError') {
        throw new Error('Request timed out');
      }
      throw err;
    }
  };
  
  // Async function with multiple API calls
  const fetchMultiple = async () => {
    try {
      setLoading(true);
      const [users, posts] = await Promise.all([
        fetch('https://jsonplaceholder.typicode.com/users').then(res => res.json()),
        fetch('https://jsonplaceholder.typicode.com/posts').then(res => res.json())
      ]);
      setData({ users, posts });
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };
  
  // Async function with retry
  const fetchWithRetry = async (url, retries = 3) => {
    for (let i = 0; i < retries; i++) {
      try {
        const response = await fetch(url);
        return await response.json();
      } catch (err) {
        if (i === retries - 1) throw err;
        await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
      }
    }
  };
  
  // Async function in useEffect
  React.useEffect(() => {
    fetchData();
  }, []);
  
  return (
    <View style={{ flex: 1, padding: 20 }}>
      {loading && <ActivityIndicator size="large" />}
      {error && <Text style={{ color: 'red' }}>Error: {error}</Text>}
      
      {data && (
        <FlatList
          data={Array.isArray(data) ? data : []}
          renderItem={({ item }) => (
            <Text>{item.name}</Text>
          )}
          keyExtractor={(item) => item.id.toString()}
        />
      )}
      
      <Button title="Fetch Data" onPress={fetchData} />
      <Button title="Fetch Multiple" onPress={fetchMultiple} />
    </View>
  );
};

export default App;
Advanced
22. What are custom hooks for async operations?

Custom hooks for async operations encapsulate fetching logic, loading states, error handling, and data management.

  • useAsync: Handle async operations
  • useFetch: Data fetching with state
  • usePolling: Regular data updates
  • usePagination: Paginated data loading
  • useDebounce: Debounced async operations
typescript
// Custom Hooks for Async Operations
import React, { useState, useEffect, useCallback } from 'react';
import { View, Text, Button, ActivityIndicator } from 'react-native';

// Custom hook for async operations
const useAsync = (asyncFn) => {
  const [state, setState] = useState({
    data: null,
    loading: false,
    error: null
  });
  
  const execute = useCallback(async (...args) => {
    try {
      setState(prev => ({ ...prev, loading: true, error: null }));
      const result = await asyncFn(...args);
      setState(prev => ({ ...prev, data: result, loading: false }));
      return result;
    } catch (error) {
      setState(prev => ({ ...prev, error: error.message, loading: false }));
      throw error;
    }
  }, [asyncFn]);
  
  return { ...state, execute };
};

// Custom hook for polling
const usePolling = (asyncFn, interval) => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  
  useEffect(() => {
    let mounted = true;
    let intervalId;
    
    const poll = async () => {
      try {
        if (mounted) setLoading(true);
        const result = await asyncFn();
        if (mounted) {
          setData(result);
          setError(null);
        }
      } catch (err) {
        if (mounted) setError(err.message);
      } finally {
        if (mounted) setLoading(false);
      }
    };
    
    poll();
    intervalId = setInterval(poll, interval);
    
    return () => {
      mounted = false;
      clearInterval(intervalId);
    };
  }, [asyncFn, interval]);
  
  return { data, loading, error };
};

// Custom hook for pagination
const usePagination = (asyncFn) => {
  const [data, setData] = useState([]);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const [error, setError] = useState(null);
  
  const loadMore = async () => {
    if (loading || !hasMore) return;
    
    try {
      setLoading(true);
      const result = await asyncFn(page);
      setData(prev => [...prev, ...result.items]);
      setHasMore(result.hasMore);
      setPage(prev => prev + 1);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };
  
  const reset = () => {
    setData([]);
    setPage(1);
    setHasMore(true);
    setError(null);
    loadMore();
  };
  
  return { data, loading, hasMore, error, loadMore, reset };
};

// Using custom hooks
const App = () => {
  const fetchData = async () => {
    const response = await fetch('https://api.example.com/data');
    return response.json();
  };
  
  const { data, loading, error, execute } = useAsync(fetchData);
  
  return (
    <View style={{ flex: 1, padding: 20 }}>
      {loading && <ActivityIndicator size="large" />}
      {error && <Text style={{ color: 'red' }}>Error: {error}</Text>}
      {data && <Text>Data loaded</Text>}
      <Button title="Execute" onPress={execute} />
    </View>
  );
};

export default App;
Advanced
23. What is Context API in React Native?

Context API provides a way to pass data through the component tree without passing props manually at every level.

  • createContext: Create a context
  • Provider: Provide values to the tree
  • Consumer: Access context values
  • useContext: Hook for consuming context
  • Custom providers: Create with hooks for state
typescript
// Context API in React Native
import React, { createContext, useContext, useState } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';

// Create contexts
const ThemeContext = createContext();
const UserContext = createContext();
const SettingsContext = createContext();

// Custom hooks for contexts
const useTheme = () => {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme must be used within ThemeProvider');
  }
  return context;
};

const useUser = () => {
  const context = useContext(UserContext);
  if (!context) {
    throw new Error('useUser must be used within UserProvider');
  }
  return context;
};

// Theme provider
const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useState('light');
  
  const toggleTheme = () => {
    setTheme(theme === 'light' ? 'dark' : 'light');
  };
  
  const value = {
    theme,
    toggleTheme,
    colors: theme === 'light' ? {
      background: '#ffffff',
      text: '#000000',
      primary: '#007AFF'
    } : {
      background: '#000000',
      text: '#ffffff',
      primary: '#007AFF'
    }
  };
  
  return (
    <ThemeContext.Provider value={value}>
      {children}
    </ThemeContext.Provider>
  );
};

// User provider
const UserProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  
  const login = (userData) => {
    setUser(userData);
  };
  
  const logout = () => {
    setUser(null);
  };
  
  return (
    <UserContext.Provider value={{ user, login, logout }}>
      {children}
    </UserContext.Provider>
  );
};

// Combined provider
const AppProvider = ({ children }) => {
  return (
    <ThemeProvider>
      <UserProvider>
        {children}
      </UserProvider>
    </ThemeProvider>
  );
};

// Components using context
const SettingsScreen = () => {
  const { theme, toggleTheme, colors } = useTheme();
  const { user } = useUser();
  
  return (
    <View style={[styles.container, { backgroundColor: colors.background }]}>
      <Text style={[styles.text, { color: colors.text }]}>User: {user?.name || 'Not logged in'}</Text>
      <Text style={[styles.text, { color: colors.text }]}>Theme: {theme}</Text>
      <Button title="Toggle Theme" onPress={toggleTheme} />
    </View>
  );
};

const ProfileScreen = () => {
  const { colors } = useTheme();
  const { user, logout } = useUser();
  
  if (!user) {
    return (
      <View style={[styles.container, { backgroundColor: colors.background }]}>
        <Text style={[styles.text, { color: colors.text }]}>Not logged in</Text>
      </View>
    );
  }
  
  return (
    <View style={[styles.container, { backgroundColor: colors.background }]}>
      <Text style={[styles.text, { color: colors.text }]}>Name: {user.name}</Text>
      <Text style={[styles.text, { color: colors.text }]}>Email: {user.email}</Text>
      <Button title="Logout" onPress={logout} />
    </View>
  );
};

const App = () => {
  const { login } = useUser();
  
  React.useEffect(() => {
    login({ name: 'Alice', email: 'alice@example.com' });
  }, []);
  
  return (
    <View style={{ flex: 1 }}>
      <SettingsScreen />
      <ProfileScreen />
    </View>
  );
};

// Main app with provider
const MainApp = () => {
  return (
    <AppProvider>
      <App />
    </AppProvider>
  );
};

const styles = StyleSheet.create({
  container: { padding: 20, margin: 10, borderWidth: 1, borderRadius: 5 },
  text: { fontSize: 16, marginBottom: 10 }
});

export default MainApp;
Advanced
24. How to implement Redux-like state management?

Redux-like state management can be implemented using useReducer hook and Context API for global state management.

  • useReducer: Manage complex state
  • Context: Provide state globally
  • Actions: Define action types
  • Reducers: Pure functions for state updates
  • Custom hooks: Use context with custom hook
typescript
// Redux-like State Management in React Native
import React, { createContext, useContext, useReducer } from 'react';
import { View, Text, Button, FlatList, StyleSheet } from 'react-native';

// Action types
const ADD_TODO = 'ADD_TODO';
const TOGGLE_TODO = 'TOGGLE_TODO';
const DELETE_TODO = 'DELETE_TODO';
const SET_FILTER = 'SET_FILTER';

// Initial state
const initialState = {
  todos: [],
  filter: 'all'
};

// Reducer function
const todoReducer = (state, action) => {
  switch (action.type) {
    case ADD_TODO:
      return {
        ...state,
        todos: [...state.todos, {
          id: Date.now(),
          text: action.payload,
          completed: false
        }]
      };
    case TOGGLE_TODO:
      return {
        ...state,
        todos: state.todos.map(todo =>
          todo.id === action.payload
            ? { ...todo, completed: !todo.completed }
            : todo
        )
      };
    case DELETE_TODO:
      return {
        ...state,
        todos: state.todos.filter(todo => todo.id !== action.payload)
      };
    case SET_FILTER:
      return {
        ...state,
        filter: action.payload
      };
    default:
      return state;
  }
};

// Context
const TodoContext = createContext();

// Provider
const TodoProvider = ({ children }) => {
  const [state, dispatch] = useReducer(todoReducer, initialState);
  
  const addTodo = (text) => {
    dispatch({ type: ADD_TODO, payload: text });
  };
  
  const toggleTodo = (id) => {
    dispatch({ type: TOGGLE_TODO, payload: id });
  };
  
  const deleteTodo = (id) => {
    dispatch({ type: DELETE_TODO, payload: id });
  };
  
  const setFilter = (filter) => {
    dispatch({ type: SET_FILTER, payload: filter });
  };
  
  const getFilteredTodos = () => {
    switch (state.filter) {
      case 'active':
        return state.todos.filter(todo => !todo.completed);
      case 'completed':
        return state.todos.filter(todo => todo.completed);
      default:
        return state.todos;
    }
  };
  
  return (
    <TodoContext.Provider value={{
      todos: state.todos,
      filter: state.filter,
      filteredTodos: getFilteredTodos(),
      addTodo,
      toggleTodo,
      deleteTodo,
      setFilter
    }}>
      {children}
    </TodoContext.Provider>
  );
};

// Custom hook
const useTodos = () => {
  const context = useContext(TodoContext);
  if (!context) {
    throw new Error('useTodos must be used within TodoProvider');
  }
  return context;
};

// Components
const TodoList = () => {
  const { filteredTodos, toggleTodo, deleteTodo } = useTodos();
  
  return (
    <FlatList
      data={filteredTodos}
      renderItem={({ item }) => (
        <View style={styles.todoItem}>
          <Text
            style={[
              styles.todoText,
              item.completed && styles.completedText
            ]}
            onPress={() => toggleTodo(item.id)}
          >
            {item.text}
          </Text>
          <Button title="Delete" onPress={() => deleteTodo(item.id)} />
        </View>
      )}
      keyExtractor={(item) => item.id.toString()}
    />
  );
};

const TodoInput = () => {
  const [text, setText] = React.useState('');
  const { addTodo } = useTodos();
  
  const handleSubmit = () => {
    if (text.trim()) {
      addTodo(text);
      setText('');
    }
  };
  
  return (
    <View style={styles.inputContainer}>
      <TextInput
        style={styles.input}
        placeholder="Enter todo"
        value={text}
        onChangeText={setText}
        onSubmitEditing={handleSubmit}
      />
      <Button title="Add" onPress={handleSubmit} />
    </View>
  );
};

const TodoFilter = () => {
  const { filter, setFilter } = useTodos();
  const filters = ['all', 'active', 'completed'];
  
  return (
    <View style={styles.filterContainer}>
      {filters.map((f) => (
        <Button
          key={f}
          title={f}
          onPress={() => setFilter(f)}
          disabled={filter === f}
        />
      ))}
    </View>
  );
};

const App = () => {
  return (
    <TodoProvider>
      <View style={styles.container}>
        <Text style={styles.title}>Todo App</Text>
        <TodoInput />
        <TodoFilter />
        <TodoList />
      </View>
    </TodoProvider>
  );
};

// TextInput component (since we're using it in TodoInput)
const TextInput = ({ style, ...props }) => (
  <View style={[styles.input, style]}>
    <Text>{props.value}</Text>
  </View>
);

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20 },
  title: { fontSize: 24, fontWeight: 'bold', marginBottom: 20 },
  inputContainer: { flexDirection: 'row', marginBottom: 10 },
  input: { flex: 1, borderWidth: 1, padding: 10, marginRight: 10 },
  todoItem: { flexDirection: 'row', justifyContent: 'space-between', padding: 10, borderWidth: 1, marginBottom: 5 },
  todoText: { fontSize: 16 },
  completedText: { textDecorationLine: 'line-through', color: 'gray' },
  filterContainer: { flexDirection: 'row', justifyContent: 'space-around', marginVertical: 10 }
});

export default App;
Advanced
25. How to implement navigation in React Native?

Navigation in React Native is implemented using React Navigation library with Stack, Tab, and Drawer navigators.

  • Stack Navigator: Screen stack navigation
  • Tab Navigator: Bottom/top tab navigation
  • Drawer Navigator: Side menu navigation
  • Nested navigators: Combine navigator types
  • Navigation hooks: useNavigation, useRoute
typescript
// Navigation in React Native (React Navigation)
import React from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { createDrawerNavigator } from '@react-navigation/drawer';

// Screens
const HomeScreen = ({ navigation }) => {
  return (
    <View style={styles.screen}>
      <Text style={styles.title}>Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => navigation.navigate('Details', { itemId: 42 })}
      />
      <Button
        title="Go to Profile"
        onPress={() => navigation.navigate('Profile')}
      />
    </View>
  );
};

const DetailsScreen = ({ route, navigation }) => {
  const { itemId } = route.params || {};
  
  return (
    <View style={styles.screen}>
      <Text style={styles.title}>Details Screen</Text>
      <Text>Item ID: {itemId}</Text>
      <Button
        title="Go Back"
        onPress={() => navigation.goBack()}
      />
      <Button
        title="Go Home"
        onPress={() => navigation.navigate('Home')}
      />
    </View>
  );
};

const ProfileScreen = () => {
  return (
    <View style={styles.screen}>
      <Text style={styles.title}>Profile Screen</Text>
    </View>
  );
};

const SettingsScreen = () => {
  return (
    <View style={styles.screen}>
      <Text style={styles.title}>Settings Screen</Text>
    </View>
  );
};

// Stack Navigator
const Stack = createStackNavigator();
const StackNavigator = () => {
  return (
    <Stack.Navigator
      initialRouteName="Home"
      screenOptions={{
        headerStyle: { backgroundColor: '#007AFF' },
        headerTintColor: '#fff',
        headerTitleStyle: { fontWeight: 'bold' }
      }}
    >
      <Stack.Screen name="Home" component={HomeScreen} />
      <Stack.Screen name="Details" component={DetailsScreen} />
      <Stack.Screen name="Profile" component={ProfileScreen} />
    </Stack.Navigator>
  );
};

// Tab Navigator
const Tab = createBottomTabNavigator();
const TabNavigator = () => {
  return (
    <Tab.Navigator>
      <Tab.Screen name="Home" component={HomeScreen} />
      <Tab.Screen name="Profile" component={ProfileScreen} />
      <Tab.Screen name="Settings" component={SettingsScreen} />
    </Tab.Navigator>
  );
};

// Drawer Navigator
const Drawer = createDrawerNavigator();
const DrawerNavigator = () => {
  return (
    <Drawer.Navigator>
      <Drawer.Screen name="Home" component={HomeScreen} />
      <Drawer.Screen name="Profile" component={ProfileScreen} />
      <Drawer.Screen name="Settings" component={SettingsScreen} />
    </Drawer.Navigator>
  );
};

// Nested Navigation
const App = () => {
  return (
    <NavigationContainer>
      <StackNavigator />
    </NavigationContainer>
  );
};

const styles = StyleSheet.create({
  screen: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20 },
  title: { fontSize: 24, fontWeight: 'bold', marginBottom: 20 }
});

export default App;
Advanced
26. How to use lists in React Native?

React Native provides FlatList and SectionList components for efficient list rendering with virtualization and scroll support.

  • FlatList: Rendering flat lists
  • SectionList: Rendering sectioned lists
  • Virtualization: Efficient rendering
  • Pagination: onEndReached for loading more
  • Pull to refresh: onRefresh and refreshing
typescript
// Lists and FlatList in React Native
import React, { useState } from 'react';
import { View, Text, FlatList, SectionList, StyleSheet, Button } from 'react-native';

// Basic FlatList
const BasicFlatList = () => {
  const [data, setData] = useState([
    { id: '1', name: 'Item 1' },
    { id: '2', name: 'Item 2' },
    { id: '3', name: 'Item 3' },
    { id: '4', name: 'Item 4' },
    { id: '5', name: 'Item 5' }
  ]);
  
  const renderItem = ({ item }) => (
    <View style={styles.item}>
      <Text style={styles.itemText}>{item.name}</Text>
    </View>
  );
  
  return (
    <FlatList
      data={data}
      renderItem={renderItem}
      keyExtractor={(item) => item.id}
      ItemSeparatorComponent={() => <View style={styles.separator} />}
      ListHeaderComponent={<Text style={styles.header}>Header</Text>}
      ListFooterComponent={<Text style={styles.footer}>Footer</Text>}
      onRefresh={() => console.log('Refreshing')}
      refreshing={false}
    />
  );
};

// SectionList
const SectionListExample = () => {
  const sections = [
    {
      title: 'Section 1',
      data: ['Item 1A', 'Item 1B', 'Item 1C']
    },
    {
      title: 'Section 2',
      data: ['Item 2A', 'Item 2B', 'Item 2C']
    },
    {
      title: 'Section 3',
      data: ['Item 3A', 'Item 3B', 'Item 3C']
    }
  ];
  
  return (
    <SectionList
      sections={sections}
      keyExtractor={(item, index) => item + index}
      renderItem={({ item }) => (
        <View style={styles.sectionItem}>
          <Text>{item}</Text>
        </View>
      )}
      renderSectionHeader={({ section }) => (
        <View style={styles.sectionHeader}>
          <Text style={styles.sectionHeaderText}>{section.title}</Text>
        </View>
      )}
    />
  );
};

// FlatList with pagination
const PaginatedList = () => {
  const [data, setData] = useState([]);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  
  const loadMore = () => {
    if (loading || !hasMore) return;
    
    setLoading(true);
    // Simulate API call
    setTimeout(() => {
      const newItems = Array.from({ length: 10 }, (_, i) => ({
        id: `${page}-${i}`,
        name: `Item ${page * 10 + i + 1}`
      }));
      setData([...data, ...newItems]);
      setPage(page + 1);
      setHasMore(page < 5);
      setLoading(false);
    }, 1000);
  };
  
  return (
    <FlatList
      data={data}
      renderItem={({ item }) => (
        <View style={styles.item}>
          <Text>{item.name}</Text>
        </View>
      )}
      keyExtractor={(item) => item.id}
      onEndReached={loadMore}
      onEndReachedThreshold={0.5}
      ListFooterComponent={
        loading && <Text style={styles.loading}>Loading more...</Text>
      }
    />
  );
};

// FlatList with complex items
const ComplexList = () => {
  const data = [
    { id: '1', title: 'Item 1', description: 'Description 1' },
    { id: '2', title: 'Item 2', description: 'Description 2' },
    { id: '3', title: 'Item 3', description: 'Description 3' }
  ];
  
  const renderItem = ({ item }) => (
    <View style={styles.complexItem}>
      <Text style={styles.complexTitle}>{item.title}</Text>
      <Text style={styles.complexDescription}>{item.description}</Text>
      <Button title="Action" onPress={() => console.log('Pressed', item.id)} />
    </View>
  );
  
  return (
    <FlatList
      data={data}
      renderItem={renderItem}
      keyExtractor={(item) => item.id}
    />
  );
};

// App
const App = () => {
  return (
    <View style={styles.container}>
      <BasicFlatList />
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20 },
  item: { padding: 15, backgroundColor: '#f9f9f9' },
  itemText: { fontSize: 16 },
  separator: { height: 1, backgroundColor: '#ccc' },
  header: { fontSize: 20, fontWeight: 'bold', padding: 10 },
  footer: { fontSize: 16, padding: 10, textAlign: 'center' },
  sectionHeader: { padding: 10, backgroundColor: '#e0e0e0' },
  sectionHeaderText: { fontSize: 18, fontWeight: 'bold' },
  sectionItem: { padding: 10, borderWidth: 1, borderColor: '#ccc' },
  loading: { textAlign: 'center', padding: 10 },
  complexItem: { padding: 15, borderWidth: 1, marginBottom: 10 },
  complexTitle: { fontSize: 18, fontWeight: 'bold' },
  complexDescription: { fontSize: 14, color: '#666', marginVertical: 5 }
});

export default App;
Advanced
27. How to handle forms in React Native?

Forms in React Native use TextInput, TouchableOpacity, and validation logic with state management for form data and errors.

  • TextInput: Input fields
  • State management: useState for form data
  • Validation: Validate on submit or change
  • Error handling: Display error messages
  • Submission: Handle form submission
typescript
// Forms and Input in React Native
import React, { useState } from 'react';
import { View, Text, TextInput, Button, StyleSheet, ScrollView, Alert } from 'react-native';

const App = () => {
  const [form, setForm] = useState({
    name: '',
    email: '',
    password: '',
    phone: '',
    age: ''
  });
  
  const [errors, setErrors] = useState({});
  
  const handleChange = (field, value) => {
    setForm({ ...form, [field]: value });
    // Clear error when user types
    if (errors[field]) {
      setErrors({ ...errors, [field]: null });
    }
  };
  
  const validate = () => {
    const newErrors = {};
    
    if (!form.name.trim()) {
      newErrors.name = 'Name is required';
    }
    
    if (!form.email.trim()) {
      newErrors.email = 'Email is required';
    } else if (!/S+@S+.S+/.test(form.email)) {
      newErrors.email = 'Email is invalid';
    }
    
    if (!form.password.trim()) {
      newErrors.password = 'Password is required';
    } else if (form.password.length < 6) {
      newErrors.password = 'Password must be at least 6 characters';
    }
    
    if (form.phone && !/^d{10}$/.test(form.phone)) {
      newErrors.phone = 'Phone must be 10 digits';
    }
    
    if (form.age && (isNaN(form.age) || parseInt(form.age) < 0 || parseInt(form.age) > 150)) {
      newErrors.age = 'Age must be between 0 and 150';
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  
  const handleSubmit = () => {
    if (validate()) {
      Alert.alert('Success', 'Form submitted successfully!');
      console.log('Form data:', form);
    }
  };
  
  const handleReset = () => {
    setForm({
      name: '',
      email: '',
      password: '',
      phone: '',
      age: ''
    });
    setErrors({});
  };
  
  return (
    <ScrollView style={styles.container}>
      <Text style={styles.title}>Registration Form</Text>
      
      <View style={styles.field}>
        <Text style={styles.label}>Name *</Text>
        <TextInput
          style={[styles.input, errors.name && styles.inputError]}
          placeholder="Enter your name"
          value={form.name}
          onChangeText={(text) => handleChange('name', text)}
        />
        {errors.name && <Text style={styles.errorText}>{errors.name}</Text>}
      </View>
      
      <View style={styles.field}>
        <Text style={styles.label}>Email *</Text>
        <TextInput          style={[styles.input, errors.email && styles.inputError]}
          placeholder="Enter your email"
          keyboardType="email-address"
          autoCapitalize="none"
          value={form.email}
          onChangeText={(text) => handleChange('email', text)}
        />
        {errors.email && <Text style={styles.errorText}>{errors.email}</Text>}
      </View>
      
      <View style={styles.field}>
        <Text style={styles.label}>Password *</Text>
        <TextInput
          style={[styles.input, errors.password && styles.inputError]}
          placeholder="Enter your password"
          secureTextEntry
          value={form.password}
          onChangeText={(text) => handleChange('password', text)}
        />
        {errors.password && <Text style={styles.errorText}>{errors.password}</Text>}
      </View>
      
      <View style={styles.field}>
        <Text style={styles.label}>Phone</Text>
        <TextInput
          style={[styles.input, errors.phone && styles.inputError]}
          placeholder="Enter your phone (10 digits)"
          keyboardType="phone-pad"
          value={form.phone}
          onChangeText={(text) => handleChange('phone', text)}
        />
        {errors.phone && <Text style={styles.errorText}>{errors.phone}</Text>}
      </View>
      
      <View style={styles.field}>
        <Text style={styles.label}>Age</Text>
        <TextInput
          style={[styles.input, errors.age && styles.inputError]}
          placeholder="Enter your age"
          keyboardType="number-pad"
          value={form.age}
          onChangeText={(text) => handleChange('age', text)}
        />
        {errors.age && <Text style={styles.errorText}>{errors.age}</Text>}
      </View>
      
      <View style={styles.buttonContainer}>
        <Button title="Submit" onPress={handleSubmit} />
        <Button title="Reset" onPress={handleReset} color="#666" />
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20 },
  title: { fontSize: 24, fontWeight: 'bold', textAlign: 'center', marginBottom: 20 },
  field: { marginBottom: 15 },
  label: { fontSize: 16, fontWeight: 'bold', marginBottom: 5 },
  input: { borderWidth: 1, borderColor: '#ccc', padding: 10, borderRadius: 5, fontSize: 16 },
  inputError: { borderColor: 'red' },
  errorText: { color: 'red', fontSize: 14, marginTop: 5 },
  buttonContainer: { flexDirection: 'row', justifyContent: 'space-around', marginTop: 20 }
});

export default App;
Advanced
28. How to integrate APIs in React Native?

API integration in React Native uses fetch or axios with async/await for making HTTP requests and handling responses.

  • fetch API: Native JavaScript API
  • axios: Third-party library
  • async/await: Handle async operations
  • Error handling: Try-catch blocks
  • Loading states: Show loading indicators
typescript
// API Integration in React Native
import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, ActivityIndicator, Button, StyleSheet, Alert } from 'react-native';

// API service
const API = {
  baseURL: 'https://jsonplaceholder.typicode.com',
  
  getUsers: async () => {
    const response = await fetch(`${API.baseURL}/users`);
    if (!response.ok) throw new Error('Failed to fetch users');
    return response.json();
  },
  
  getUserPosts: async (userId) => {
    const response = await fetch(`${API.baseURL}/posts?userId=${userId}`);
    if (!response.ok) throw new Error('Failed to fetch posts');
    return response.json();
  },
  
  createPost: async (post) => {
    const response = await fetch(`${API.baseURL}/posts`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(post)
    });
    if (!response.ok) throw new Error('Failed to create post');
    return response.json();
  }
};

// Custom hook for API calls
const useAPI = (apiFn, initialData = null) => {
  const [data, setData] = useState(initialData);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  
  const execute = async (...args) => {
    try {
      setLoading(true);
      setError(null);
      const result = await apiFn(...args);
      setData(result);
      return result;
    } catch (err) {
      setError(err.message);
      Alert.alert('Error', err.message);
      return null;
    } finally {
      setLoading(false);
    }
  };
  
  return { data, loading, error, execute };
};

// Users list component
const UsersList = ({ onSelectUser }) => {
  const { data: users, loading, error, execute } = useAPI(API.getUsers);
  
  useEffect(() => {
    execute();
  }, []);
  
  if (loading) {
    return (
      <View style={styles.centerContainer}>
        <ActivityIndicator size="large" />
        <Text>Loading users...</Text>
      </View>
    );
  }
  
  if (error) {
    return (
      <View style={styles.centerContainer}>
        <Text style={styles.errorText}>Error: {error}</Text>
        <Button title="Retry" onPress={() => execute()} />
      </View>
    );
  }
  
  return (
    <FlatList
      data={users}
      renderItem={({ item }) => (
        <View style={styles.userItem}>
          <Text style={styles.userName}>{item.name}</Text>
          <Text style={styles.userEmail}>{item.email}</Text>
          <Button title="View Posts" onPress={() => onSelectUser(item.id)} />
        </View>
      )}
      keyExtractor={(item) => item.id.toString()}
    />
  );
};

// Posts list component
const PostsList = ({ userId }) => {
  const { data: posts, loading, error, execute } = useAPI(API.getUserPosts);
  
  useEffect(() => {
    if (userId) {
      execute(userId);
    }
  }, [userId]);
  
  if (loading) {
    return (
      <View style={styles.centerContainer}>
        <ActivityIndicator size="large" />
        <Text>Loading posts...</Text>
      </View>
    );
  }
  
  if (error) {
    return (
      <View style={styles.centerContainer}>
        <Text style={styles.errorText}>Error: {error}</Text>
      </View>
    );
  }
  
  return (
    <FlatList
      data={posts}
      renderItem={({ item }) => (
        <View style={styles.postItem}>
          <Text style={styles.postTitle}>{item.title}</Text>
          <Text style={styles.postBody}>{item.body}</Text>
        </View>
      )}
      keyExtractor={(item) => item.id.toString()}
    />
  );
};

// Create post component
const CreatePost = ({ userId, onPostCreated }) => {
  const [title, setTitle] = useState('');
  const [body, setBody] = useState('');
  const { loading, execute } = useAPI(API.createPost);
  
  const handleSubmit = async () => {
    if (!title.trim() || !body.trim()) {
      Alert.alert('Error', 'Title and body are required');
      return;
    }
    
    const post = {
      userId,
      title,
      body
    };
    
    const result = await execute(post);
    if (result) {
      setTitle('');
      setBody('');
      if (onPostCreated) onPostCreated(result);
    }
  };
  
  return (
    <View style={styles.createPostContainer}>
      <Text style={styles.createPostTitle}>Create Post</Text>
      <TextInput
        style={styles.input}
        placeholder="Post title"
        value={title}
        onChangeText={setTitle}
      />
      <TextInput
        style={[styles.input, styles.textArea]}
        placeholder="Post body"
        value={body}
        onChangeText={setBody}
        multiline
        numberOfLines={4}
      />
      <Button
        title={loading ? 'Creating...' : 'Create Post'}
        onPress={handleSubmit}
        disabled={loading}
      />
    </View>
  );
};

// Main App
const App = () => {
  const [selectedUserId, setSelectedUserId] = useState(null);
  
  return (
    <View style={styles.container}>
      {selectedUserId ? (
        <>
          <Button title="Back to Users" onPress={() => setSelectedUserId(null)} />
          <PostsList userId={selectedUserId} />
          <CreatePost userId={selectedUserId} />
        </>
      ) : (
        <UsersList onSelectUser={setSelectedUserId} />
      )}
    </View>
  );
};

// TextInput component
const TextInput = ({ style, ...props }) => (
  <View style={style}>
    <Text>{props.value}</Text>
  </View>
);

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20 },
  centerContainer: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  userItem: { padding: 15, borderWidth: 1, marginBottom: 10, borderRadius: 5 },
  userName: { fontSize: 18, fontWeight: 'bold' },
  userEmail: { fontSize: 14, color: '#666', marginBottom: 10 },
  postItem: { padding: 15, borderWidth: 1, marginBottom: 10, borderRadius: 5 },
  postTitle: { fontSize: 16, fontWeight: 'bold' },
  postBody: { fontSize: 14, color: '#666', marginTop: 5 },
  errorText: { color: 'red', fontSize: 16 },
  createPostContainer: { padding: 15, borderWidth: 1, borderRadius: 5, marginTop: 20 },
  createPostTitle: { fontSize: 18, fontWeight: 'bold', marginBottom: 10 },
  input: { borderWidth: 1, padding: 10, marginBottom: 10, borderRadius: 5 },
  textArea: { height: 100, textAlignVertical: 'top' }
});

export default App;
Advanced
29. How to use modals in React Native?

Modals in React Native are created using the Modal component with animation types and transparent overlays for popup dialogs.

  • Modal component: Basic modal
  • Animation types: slide, fade, none
  • Transparent: Overlay background
  • Custom modals: Styled modal components
  • Alert: Built-in alert dialog
typescript
// Modals and Popups in React Native
import React, { useState } from 'react';
import { View, Text, Button, Modal, StyleSheet, TouchableOpacity, Alert } from 'react-native';

const App = () => {
  const [modalVisible, setModalVisible] = useState(false);
  const [modalType, setModalType] = useState('basic');
  
  // Basic Modal
  const BasicModal = () => (
    <Modal
      animationType="slide"
      transparent={true}
      visible={modalVisible}
      onRequestClose={() => setModalVisible(false)}
    >
      <View style={styles.modalOverlay}>
        <View style={styles.modalContent}>
          <Text style={styles.modalTitle}>Basic Modal</Text>
          <Text style={styles.modalText}>This is a basic modal dialog.</Text>
          <Button title="Close" onPress={() => setModalVisible(false)} />
        </View>
      </View>
    </Modal>
  );
  
  // Custom Modal
  const CustomModal = () => (
    <Modal
      animationType="fade"
      transparent={true}
      visible={modalVisible}
      onRequestClose={() => setModalVisible(false)}
    >
      <View style={styles.modalOverlay}>
        <View style={[styles.modalContent, styles.customModal]}>
          <Text style={styles.modalTitle}>Custom Modal</Text>
          <Text style={styles.modalText}>This is a custom modal with actions.</Text>
          <View style={styles.modalActions}>
            <TouchableOpacity
              style={[styles.modalButton, styles.cancelButton]}
              onPress={() => setModalVisible(false)}
            >
              <Text style={styles.modalButtonText}>Cancel</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={[styles.modalButton, styles.confirmButton]}
              onPress={() => {
                Alert.alert('Confirmed', 'Action confirmed!');
                setModalVisible(false);
              }}
            >
              <Text style={styles.modalButtonText}>Confirm</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </Modal>
  );
  
  // Full Screen Modal
  const FullScreenModal = () => (
    <Modal
      animationType="slide"
      visible={modalVisible}
      onRequestClose={() => setModalVisible(false)}
    >
      <View style={styles.fullScreenModal}>
        <Text style={styles.modalTitle}>Full Screen Modal</Text>
        <Text style={styles.modalText}>This is a full screen modal.</Text>
        <Button title="Close" onPress={() => setModalVisible(false)} />
      </View>
    </Modal>
  );
  
  // Alert Modal
  const showAlert = () => {
    Alert.alert(
      'Alert Title',
      'This is an alert message with options.',
      [
        {
          text: 'Cancel',
          onPress: () => console.log('Cancel Pressed'),
          style: 'cancel'
        },
        {
          text: 'OK',
          onPress: () => console.log('OK Pressed')
        },
        {
          text: 'Delete',
          onPress: () => console.log('Delete Pressed'),
          style: 'destructive'
        }
      ],
      { cancelable: true }
    );
  };
  
  // Prompt Alert (simple)
  const showPrompt = () => {
    Alert.prompt(
      'Enter Name',
      'Please enter your name:',
      [
        {
          text: 'Cancel',
          onPress: () => console.log('Cancel Pressed'),
          style: 'cancel'
        },
        {
          text: 'OK',
          onPress: (text) => console.log('Name entered:', text)
        }
      ],
      'plain-text',
      'Default name'
    );
  };
  
  return (
    <View style={styles.container}>
      <Text style={styles.title}>Modal Examples</Text>
      
      <Button
        title="Open Basic Modal"
        onPress={() => {
          setModalType('basic');
          setModalVisible(true);
        }}
      />
      
      <Button
        title="Open Custom Modal"
        onPress={() => {
          setModalType('custom');
          setModalVisible(true);
        }}
      />
      
      <Button
        title="Open Full Screen Modal"
        onPress={() => {
          setModalType('fullscreen');
          setModalVisible(true);
        }}
      />
      
      <Button title="Show Alert" onPress={showAlert} />
      <Button title="Show Prompt" onPress={showPrompt} />
      
      {modalType === 'basic' && <BasicModal />}
      {modalType === 'custom' && <CustomModal />}
      {modalType === 'fullscreen' && <FullScreenModal />}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    gap: 10
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
    textAlign: 'center'
  },
  modalOverlay: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.5)'
  },
  modalContent: {
    backgroundColor: 'white',
    padding: 20,
    borderRadius: 10,
    minWidth: 300
  },
  customModal: {
    backgroundColor: '#f0f0f0',
    minWidth: 350
  },
  fullScreenModal: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
    backgroundColor: 'white'
  },
  modalTitle: {
    fontSize: 20,
    fontWeight: 'bold',
    marginBottom: 10
  },
  modalText: {
    fontSize: 16,
    marginBottom: 20
  },
  modalActions: {
    flexDirection: 'row',
    justifyContent: 'space-around'
  },
  modalButton: {
    padding: 10,
    borderRadius: 5,
    minWidth: 80,
    alignItems: 'center'
  },
  cancelButton: {
    backgroundColor: '#ccc'
  },
  confirmButton: {
    backgroundColor: '#007AFF'
  },
  modalButtonText: {
    color: 'white',
    fontWeight: 'bold'
  }
});

export default App;
Advanced
30. How to style in React Native?

Styling in React Native uses StyleSheet for defining styles with a subset of CSS properties, supporting flexbox and platform-specific styles.

  • StyleSheet: StyleSheet.create()
  • Flexbox: Layout system
  • Platform-specific: Platform.select
  • Dynamic styles: Inline styles
  • Theming: Dark mode support
typescript
// Styling in React Native
import React from 'react';
import { View, Text, StyleSheet, Dimensions, Platform, StatusBar } from 'react-native';

// Get screen dimensions
const { width, height } = Dimensions.get('window');

// Platform specific styles
const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    paddingTop: Platform.OS === 'ios' ? 20 : StatusBar.currentHeight,
    backgroundColor: '#f5f5f5'
  },
  box: {
    width: width * 0.8,
    height: height * 0.3,
    backgroundColor: '#007AFF',
    borderRadius: 10,
    justifyContent: 'center',
    alignItems: 'center',
    margin: 10,
    // Shadow for iOS
    ...Platform.select({
      ios: {
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.25,
        shadowRadius: 3.84,
      },
      android: {
        elevation: 5,
      },
    }),
  },
  text: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#ffffff'
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    flexWrap: 'wrap'
  },
  card: {
    backgroundColor: '#fff',
    padding: 15,
    borderRadius: 8,
    marginBottom: 10,
    borderWidth: 1,
    borderColor: '#ddd'
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333'
  },
  subtitle: {
    fontSize: 14,
    color: '#666',
    marginTop: 5
  }
});

// Component with dynamic styling
const DynamicStyleExample = () => {
  const [pressed, setPressed] = useState(false);
  
  return (
    <TouchableOpacity
      style={[
        styles.box,
        pressed && { backgroundColor: '#FF3B30', transform: [{ scale: 0.95 }] }
      ]}
      onPressIn={() => setPressed(true)}
      onPressOut={() => setPressed(false)}
    >
      <Text style={styles.text}>
        {pressed ? 'Pressed!' : 'Press Me'}
      </Text>
    </TouchableOpacity>
  );
};

// Responsive styles
const responsiveStyles = StyleSheet.create({
  container: {
    flex: 1,
    padding: width < 400 ? 10 : 20
  },
  title: {
    fontSize: width < 400 ? 18 : 24,
    fontWeight: 'bold'
  },
  grid: {
    flexDirection: width < 400 ? 'column' : 'row',
    flexWrap: 'wrap'
  },
  item: {
    width: width < 400 ? '100%' : '48%',
    margin: width < 400 ? 5 : '1%'
  }
});

// Theme styles
const lightTheme = {
  background: '#ffffff',
  text: '#000000',
  primary: '#007AFF',
  border: '#cccccc'
};

const darkTheme = {
  background: '#000000',
  text: '#ffffff',
  primary: '#0A84FF',
  border: '#333333'
};

const ThemeExample = ({ theme }) => {
  const currentTheme = theme === 'dark' ? darkTheme : lightTheme;
  
  return (
    <View style={[styles.container, { backgroundColor: currentTheme.background }]}>
      <Text style={[styles.text, { color: currentTheme.text }]}>
        Theme Example
      </Text>
    </View>
  );
};

// App
const App = () => {
  return (
    <View style={styles.container}>
      <View style={styles.row}>
        <View style={styles.box}>
          <Text style={styles.text}>Box 1</Text>
        </View>
        <View style={[styles.box, { backgroundColor: '#FF3B30' }]}>
          <Text style={styles.text}>Box 2</Text>
        </View>
      </View>
      
      <View style={styles.card}>
        <Text style={styles.title}>Card Title</Text>
        <Text style={styles.subtitle}>This is a subtitle with some descriptive text.</Text>
      </View>
      
      <DynamicStyleExample />
      <ThemeExample theme="dark" />
    </View>
  );
};

export default App;
Coding Round
31. Reverse a string

Reverse a string using JavaScript methods or manual iteration.

  • Built-in: str.split('').reverse().join('')
  • Manual: Iterate from end to start
  • Using spread: [...str].reverse().join('')
  • Complexity: O(n) time
typescript
// Reverse a string in React Native
const reverseString = (str) => {
  return str.split('').reverse().join('');
};

// Usage in component
const App = () => {
  const [text, setText] = useState('hello');
  const reversed = reverseString(text);
  
  return (
    <View>
      <Text>Original: {text}</Text>
      <Text>Reversed: {reversed}</Text>
      <Button title="Reverse" onPress={() => setText(reverseString(text))} />
    </View>
  );
};
Coding Round
32. Check palindrome

Check if a string is a palindrome using JavaScript methods or two-pointer approach.

  • Built-in: str === str.split('').reverse().join('')
  • Two-pointer: Compare from both ends
  • Case insensitive: toLowerCase()
  • Ignoring non-alphanumeric: replace(/[^a-z0-9]/g, '')
typescript
// Check palindrome in React Native
const isPalindrome = (str) => {
  const cleaned = str.toLowerCase().replace(/[^a-z0-9]/g, '');
  return cleaned === cleaned.split('').reverse().join('');
};

// Two-pointer approach
const isPalindromeTwoPointer = (str) => {
  const cleaned = str.toLowerCase().replace(/[^a-z0-9]/g, '');
  let left = 0;
  let right = cleaned.length - 1;
  while (left < right) {
    if (cleaned[left] !== cleaned[right]) return false;
    left++;
    right--;
  }
  return true;
};

// Usage in component
const App = () => {
  const [text, setText] = useState('racecar');
  const result = isPalindrome(text);
  
  return (
    <View>
      <TextInput value={text} onChangeText={setText} />
      <Text>Is palindrome: {result ? 'Yes' : 'No'}</Text>
    </View>
  );
};
Coding Round
33. Find max in array

Find maximum value using Math.max or manual iteration.

  • Built-in: Math.max.apply(null, arr)
  • Spread: Math.max(...arr)
  • Manual: Iterate and track max
  • Complexity: O(n) time
typescript
// Find max in array in React Native
const findMax = (arr) => {
  return Math.max(...arr);
};

// Manual implementation
const findMaxManual = (arr) => {
  if (arr.length === 0) return null;
  let maxVal = arr[0];
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] > maxVal) maxVal = arr[i];
  }
  return maxVal;
};

// Usage in component
const App = () => {
  const numbers = [1, 5, 3, 9, 2];
  const maxValue = findMax(numbers);
  
  return (
    <View>
      <Text>Numbers: {numbers.join(', ')}</Text>
      <Text>Max: {maxValue}</Text>
    </View>
  );
};
Coding Round
34. Remove duplicates

Remove duplicates using Set or filter method.

  • Set: [...new Set(arr)]
  • Filter: arr.filter((item, index) => arr.indexOf(item) === index)
  • Preserve order: Set preserves insertion order
  • Complexity: O(n) time
typescript
// Remove duplicates in React Native
const removeDuplicates = (arr) => {
  return [...new Set(arr)];
};

// Preserving order
const removeDuplicatesOrder = (arr) => {
  const seen = new Set();
  return arr.filter(item => {
    if (seen.has(item)) return false;
    seen.add(item);
    return true;
  });
};

// Usage in component
const App = () => {
  const numbers = [1, 2, 2, 3, 3, 4];
  const unique = removeDuplicates(numbers);
  
  return (
    <View>
      <Text>Original: {numbers.join(', ')}</Text>
      <Text>Unique: {unique.join(', ')}</Text>
    </View>
  );
};
Coding Round
35. Merge arrays

Merge arrays using concat or spread operator.

  • concat: arr1.concat(arr2)
  • Spread: [...arr1, ...arr2]
  • Unique merge: [...new Set([...arr1, ...arr2])]
  • Complexity: O(n) time
typescript
// Merge arrays in React Native
const mergeArrays = (arr1, arr2) => {
  return [...arr1, ...arr2];
};

// Merge and remove duplicates
const mergeUnique = (arr1, arr2) => {
  return [...new Set([...arr1, ...arr2])];
};

// Usage in component
const App = () => {
  const arr1 = [1, 2, 3];
  const arr2 = [3, 4, 5];
  const merged = mergeArrays(arr1, arr2);
  const unique = mergeUnique(arr1, arr2);
  
  return (
    <View>
      <Text>Merged: {merged.join(', ')}</Text>
      <Text>Unique: {unique.join(', ')}</Text>
    </View>
  );
};
Coding Round
36. Convert string to number

Convert string to number using parseInt, parseFloat, or Number.

  • parseInt: parseInt(str, 10)
  • parseFloat: parseFloat(str)
  • Number: Number(str)
  • Safe conversion: Check with isNaN
typescript
// Convert string to number in React Native
const stringToNumber = (str) => {
  return parseInt(str, 10);
};

// Safe conversion
const stringToNumberSafe = (str) => {
  const num = parseFloat(str);
  return isNaN(num) ? null : num;
};

// Usage in component
const App = () => {
  const [input, setInput] = useState('42');
  const number = stringToNumberSafe(input);
  
  return (
    <View>
      <TextInput
        value={input}
        onChangeText={setInput}
        keyboardType="numeric"
        placeholder="Enter a number"
      />
      <Text>Number: {number !== null ? number : 'Invalid'}</Text>
    </View>
  );
};
Coding Round
37. Loop through object

Iterate through object using for...in, Object.keys, or Object.entries.

  • for...in: for (var key in obj)
  • Object.keys: Object.keys(obj).forEach
  • Object.entries: Object.entries(obj).forEach
  • hasOwnProperty: Check for own properties
typescript
// Loop through object in React Native
const loopObject = (obj) => {
  const entries = [];
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      entries.push(`${key}: ${obj[key]}`);
    }
  }
  return entries;
};

// Using Object.entries
const loopObjectEntries = (obj) => {
  return Object.entries(obj).map(([key, value]) => `${key}: ${value}`);
};

// Usage in component
const App = () => {
  const user = { name: 'Alice', age: 25, city: 'NYC' };
  const entries = loopObject(user);
  
  return (
    <View>
      {entries.map((entry, index) => (
        <Text key={index}>{entry}</Text>
      ))}
    </View>
  );
};
Coding Round
38. Delay function execution

Delay execution using setTimeout, setInterval, or Promises.

  • setTimeout: setTimeout(fn, delay)
  • setInterval: setInterval(fn, interval)
  • Promise: new Promise(resolve => setTimeout(resolve, delay))
  • async/await: await delay(1000)
typescript
// Delay function execution in React Native
const delay = (ms) => {
  return new Promise(resolve => setTimeout(resolve, ms));
};

// Usage in component
const App = () => {
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState('');
  
  const handleDelay = async () => {
    setLoading(true);
    await delay(2000);
    setLoading(false);
    setMessage('Executed after 2 seconds');
  };
  
  return (
    <View>
      {loading && <ActivityIndicator size="large" />}
      <Text>{message}</Text>
      <Button title="Delay" onPress={handleDelay} />
    </View>
  );
};
Coding Round
39. HTTP GET request

Make HTTP GET requests using fetch, axios, or XMLHttpRequest.

  • fetch: fetch(url).then(res => res.json())
  • axios: axios.get(url).then(res => res.data)
  • async/await: const response = await fetch(url)
  • Error handling: Check response status
typescript
// HTTP GET request in React Native
const fetchData = async (url) => {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return await response.json();
  } catch (error) {
    console.error('Fetch error:', error);
    throw error;
  }
};

// Usage in component
const App = () => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  
  const loadData = async () => {
    try {
      setLoading(true);
      setError(null);
      const result = await fetchData('https://jsonplaceholder.typicode.com/users');
      setData(result);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };
  
  return (
    <View>
      {loading && <ActivityIndicator size="large" />}
      {error && <Text style={{color: 'red'}}>Error: {error}</Text>}
      {data && (
        <FlatList
          data={data}
          renderItem={({item}) => <Text>{item.name}</Text>}
          keyExtractor={(item) => item.id.toString()}
        />
      )}
      <Button title="Fetch Data" onPress={loadData} />
    </View>
  );
};
Coding Round
40. Create a promise-like Deferred

Create a Deferred using Promises or custom implementation with resolve and reject functions.

  • Promise: new Promise((resolve, reject) => {})
  • Custom Deferred: Object with resolve/reject
  • then method: Handle fulfillment and rejection
  • Chain: then().catch()
typescript
// Create a promise-like Deferred in React Native
const createDeferred = () => {
  let resolve, reject;
  const promise = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });
  return { promise, resolve, reject };
};

// Usage in component
const App = () => {
  const [result, setResult] = useState('');
  
  const handleDeferred = async () => {
    const deferred = createDeferred();
    
    // Simulate async operation
    setTimeout(() => {
      deferred.resolve('Success!');
    }, 2000);
    
    try {
      const result = await deferred.promise;
      setResult(result);
    } catch (error) {
      setResult('Error: ' + error.message);
    }
  };
  
  return (
    <View>
      <Text>Result: {result}</Text>
      <Button title="Execute Deferred" onPress={handleDeferred} />
    </View>
  );
};
Coding Round
41. Factorial

Calculate factorial using recursion or iteration.

  • Recursive: n * factorial(n-1)
  • Iterative: Loop with multiplication
  • Base case: n <= 1
  • Edge cases: 0! = 1
typescript
// Factorial in React Native
const factorial = (n) => {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
};

const factorialIterative = (n) => {
  let result = 1;
  for (let i = 2; i <= n; i++) {
    result *= i;
  }
  return result;
};

// Usage in component
const App = () => {
  const [number, setNumber] = useState(5);
  const result = factorial(number);
  
  return (
    <View>
      <Text>Number: {number}</Text>
      <Text>Factorial: {result}</Text>
      <Button title="Increment" onPress={() => setNumber(number + 1)} />
      <Button title="Decrement" onPress={() => setNumber(Math.max(0, number - 1))} />
    </View>
  );
};
Coding Round
42. Fibonacci

Calculate Fibonacci using recursion, iteration, or memoization.

  • Recursive: fib(n-1) + fib(n-2)
  • Iterative: Loop with variables
  • Memoization: Cache results in object
  • Complexity: O(n) with memoization
typescript
// Fibonacci in React Native
const fibonacci = (n) => {
  if (n <= 1) return n;
  return fibonacci(n - 1) + fibonacci(n - 2);
};

const fibonacciIterative = (n) => {
  if (n <= 1) return n;
  let a = 0, b = 1;
  for (let i = 2; i <= n; i++) {
    const temp = a + b;
    a = b;
    b = temp;
  }
  return b;
};

// Memoized version
const fibMemo = {};
const fibonacciMemo = (n) => {
  if (n <= 1) return n;
  if (fibMemo[n]) return fibMemo[n];
  fibMemo[n] = fibonacciMemo(n - 1) + fibonacciMemo(n - 2);
  return fibMemo[n];
};

// Usage in component
const App = () => {
  const [n, setN] = useState(10);
  const result = fibonacciMemo(n);
  
  return (
    <View>
      <Text>Fibonacci({n}) = {result}</Text>
      <Button title="Next" onPress={() => setN(n + 1)} />
    </View>
  );
};
Coding Round
43. FizzBuzz

FizzBuzz using if-else or switch statement.

  • Modulo: i % 15 === 0
  • Order: Check 15 first
  • Range: for (var i = 1; i <= n; i++)
  • Return array: Collect results
typescript
// FizzBuzz in React Native
const fizzbuzz = (n) => {
  const result = [];
  for (let i = 1; i <= n; i++) {
    if (i % 15 === 0) {
      result.push('FizzBuzz');
    } else if (i % 3 === 0) {
      result.push('Fizz');
    } else if (i % 5 === 0) {
      result.push('Buzz');
    } else {
      result.push(String(i));
    }
  }
  return result;
};

// Usage in component
const App = () => {
  const [count, setCount] = useState(15);
  const results = fizzbuzz(count);
  
  return (
    <View>
      <FlatList
        data={results}
        renderItem={({item, index}) => (
          <Text>{index + 1}: {item}</Text>
        )}
        keyExtractor={(item, index) => index.toString()}
      />
      <Button title="More" onPress={() => setCount(count + 5)} />
    </View>
  );
};
Coding Round
44. Find missing number

Find missing number using formula or XOR method.

  • Formula: total - sum
  • XOR: XOR all numbers and indices
  • Complexity: O(n) time
  • Edge cases: Empty array, missing first or last
typescript
// Find missing number in React Native
const findMissing = (arr) => {
  const n = arr.length + 1;
  const total = n * (n + 1) / 2;
  const sum = arr.reduce((a, b) => a + b, 0);
  return total - sum;
};

// Using XOR
const findMissingXOR = (arr) => {
  const n = arr.length + 1;
  let xorSum = 0;
  for (let i = 1; i <= n; i++) {
    xorSum ^= i;
  }
  for (let i = 0; i < arr.length; i++) {
    xorSum ^= arr[i];
  }
  return xorSum;
};

// Usage in component
const App = () => {
  const numbers = [1, 2, 4, 5, 6];
  const missing = findMissing(numbers);
  
  return (
    <View>
      <Text>Array: {numbers.join(', ')}</Text>
      <Text>Missing number: {missing}</Text>
    </View>
  );
};
Coding Round
45. Find duplicates

Find duplicates using Set or filter method.

  • Set: Track seen elements
  • Filter: arr.filter((item, index) => arr.indexOf(item) !== index)
  • Counter: Object to count occurrences
  • Complexity: O(n) time
typescript
// Find duplicates in React Native
const findDuplicates = (arr) => {
  const seen = new Set();
  const duplicates = new Set();
  for (const item of arr) {
    if (seen.has(item)) {
      duplicates.add(item);
    } else {
      seen.add(item);
    }
  }
  return Array.from(duplicates);
};

// Using filter
const findDuplicatesFilter = (arr) => {
  return arr.filter((item, index) => arr.indexOf(item) !== index);
};

// Usage in component
const App = () => {
  const numbers = [1, 2, 3, 2, 4, 3];
  const duplicates = findDuplicates(numbers);
  
  return (
    <View>
      <Text>Array: {numbers.join(', ')}</Text>
      <Text>Duplicates: {duplicates.join(', ')}</Text>
    </View>
  );
};
Coding Round
46. Sum of array

Calculate sum using reduce or manual iteration.

  • reduce: arr.reduce((a, b) => a + b, 0)
  • Manual: Iterate and accumulate
  • forEach: arr.forEach(num => total += num)
  • Complexity: O(n) time
typescript
// Sum of array in React Native
const sumArray = (arr) => {
  return arr.reduce((a, b) => a + b, 0);
};

// Manual implementation
const sumArrayManual = (arr) => {
  let total = 0;
  for (let i = 0; i < arr.length; i++) {
    total += arr[i];
  }
  return total;
};

// Usage in component
const App = () => {
  const numbers = [1, 2, 3, 4, 5];
  const sum = sumArray(numbers);
  
  return (
    <View>
      <Text>Array: {numbers.join(', ')}</Text>
      <Text>Sum: {sum}</Text>
    </View>
  );
};
Coding Round
47. Average of array

Calculate average using reduce or manual division.

  • reduce: arr.reduce((a, b) => a + b, 0) / arr.length
  • Manual: Sum then divide
  • Empty array: Return 0
  • Precision: Returns number
typescript
// Average of array in React Native
const averageArray = (arr) => {
  if (arr.length === 0) return 0;
  return arr.reduce((a, b) => a + b, 0) / arr.length;
};

// Usage in component
const App = () => {
  const numbers = [1, 2, 3, 4, 5];
  const avg = averageArray(numbers);
  
  return (
    <View>
      <Text>Array: {numbers.join(', ')}</Text>
      <Text>Average: {avg}</Text>
    </View>
  );
};
Coding Round
48. Sort array ascending

Sort using sort with comparison function.

  • Sort: arr.slice().sort((a, b) => a - b)
  • In-place: arr.sort((a, b) => a - b)
  • Strings: sort((a, b) => a.localeCompare(b))
  • Complexity: O(n log n)
typescript
// Sort array ascending in React Native
const sortAscending = (arr) => {
  return [...arr].sort((a, b) => a - b);
};

// In-place sorting
const sortAscendingInPlace = (arr) => {
  return arr.sort((a, b) => a - b);
};

// Usage in component
const App = () => {
  const numbers = [5, 2, 8, 1, 9];
  const sorted = sortAscending(numbers);
  
  return (
    <View>
      <Text>Original: {numbers.join(', ')}</Text>
      <Text>Sorted: {sorted.join(', ')}</Text>
    </View>
  );
};
Coding Round
49. Sort array descending

Sort descending by reversing comparison.

  • Sort: arr.slice().sort((a, b) => b - a)
  • In-place: arr.sort((a, b) => b - a)
  • Strings: sort((a, b) => b.localeCompare(a))
  • Complexity: O(n log n)
typescript
// Sort array descending in React Native
const sortDescending = (arr) => {
  return [...arr].sort((a, b) => b - a);
};

// In-place sorting
const sortDescendingInPlace = (arr) => {
  return arr.sort((a, b) => b - a);
};

// Usage in component
const App = () => {
  const numbers = [5, 2, 8, 1, 9];
  const sorted = sortDescending(numbers);
  
  return (
    <View>
      <Text>Original: {numbers.join(', ')}</Text>
      <Text>Sorted: {sorted.join(', ')}</Text>
    </View>
  );
};
Coding Round
50. Flatten nested array

Flatten nested arrays using recursion or flat.

  • Recursive: Check if element is array
  • flat: arr.flat(Infinity)
  • reduce: reduce((acc, val) => acc.concat(Array.isArray(val) ? flatten(val) : val), [])
  • Complexity: O(n) time
typescript
// Flatten nested array in React Native
const flattenArray = (arr) => {
  const result = [];
  for (const item of arr) {
    if (Array.isArray(item)) {
      result.push(...flattenArray(item));
    } else {
      result.push(item);
    }
  }
  return result;
};

// Using reduce
const flattenArrayReduce = (arr) => {
  return arr.reduce((acc, val) => {
    return acc.concat(Array.isArray(val) ? flattenArrayReduce(val) : val);
  }, []);
};

// Using flat
const flattenArrayFlat = (arr) => {
  return arr.flat(Infinity);
};

// Usage in component
const App = () => {
  const nested = [1, [2, [3, 4], 5], 6];
  const flattened = flattenArray(nested);
  
  return (
    <View>
      <Text>Nested: {JSON.stringify(nested)}</Text>
      <Text>Flattened: {flattened.join(', ')}</Text>
    </View>
  );
};
Coding Round
51. Chunk array

Split array into chunks using slice in loop.

  • Loop: Iterate with step size
  • slice: arr.slice(i, i + size)
  • Edge case: Handle last chunk
  • Complexity: O(n) time
typescript
// Chunk array in React Native
const chunkArray = (arr, size) => {
  const chunks = [];
  for (let i = 0; i < arr.length; i += size) {
    chunks.push(arr.slice(i, i + size));
  }
  return chunks;
};

// Usage in component
const App = () => {
  const numbers = [1, 2, 3, 4, 5, 6];
  const chunks = chunkArray(numbers, 2);
  
  return (
    <View>
      <Text>Array: {numbers.join(', ')}</Text>
      <Text>Chunks:</Text>
      {chunks.map((chunk, index) => (
        <Text key={index}>[{chunk.join(', ')}]</Text>
      ))}
    </View>
  );
};
Coding Round
53. Quick sort

Quick sort using recursion and partitioning.

  • Algorithm: Choose pivot, partition, recurse
  • Time: O(n log n) average
  • In-place: Implement for performance
  • Pivot: First element or random
typescript
// Quick sort in React Native
const quickSort = (arr) => {
  if (arr.length <= 1) return arr;
  const pivot = arr[0];
  const left = [];
  const right = [];
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] < pivot) left.push(arr[i]);
    else right.push(arr[i]);
  }
  return [...quickSort(left), pivot, ...quickSort(right)];
};

// In-place quick sort
const quickSortInPlace = (arr, low = 0, high = arr.length - 1) => {
  if (low < high) {
    const pi = partition(arr, low, high);
    quickSortInPlace(arr, low, pi - 1);
    quickSortInPlace(arr, pi + 1, high);
  }
  return arr;
};

const partition = (arr, low, high) => {
  const pivot = arr[high];
  let i = low - 1;
  for (let j = low; j < high; j++) {
    if (arr[j] <= pivot) {
      i++;
      [arr[i], arr[j]] = [arr[j], arr[i]];
    }
  }
  [arr[i + 1], arr[high]] = [arr[high], arr[i + 1]];
  return i + 1;
};

// Usage in component
const App = () => {
  const numbers = [5, 3, 8, 4, 2, 7, 1, 6];
  const sorted = quickSort(numbers);
  
  return (
    <View>
      <Text>Original: {numbers.join(', ')}</Text>
      <Text>Sorted: {sorted.join(', ')}</Text>
    </View>
  );
};
Coding Round
54. Merge sort

Merge sort using divide-and-conquer and merging.

  • Algorithm: Divide, sort, merge
  • Time: O(n log n)
  • Stable: Maintains relative order
  • Space: O(n) auxiliary space
typescript
// Merge sort in React Native
const mergeSort = (arr) => {
  if (arr.length <= 1) return arr;
  const mid = Math.floor(arr.length / 2);
  const left = mergeSort(arr.slice(0, mid));
  const right = mergeSort(arr.slice(mid));
  return merge(left, right);
};

const merge = (left, right) => {
  const result = [];
  let i = 0, j = 0;
  while (i < left.length && j < right.length) {
    if (left[i] <= right[j]) {
      result.push(left[i++]);
    } else {
      result.push(right[j++]);
    }
  }
  while (i < left.length) result.push(left[i++]);
  while (j < right.length) result.push(right[j++]);
  return result;
};

// Usage in component
const App = () => {
  const numbers = [5, 3, 8, 4, 2, 7, 1, 6];
  const sorted = mergeSort(numbers);
  
  return (
    <View>
      <Text>Original: {numbers.join(', ')}</Text>
      <Text>Sorted: {sorted.join(', ')}</Text>
    </View>
  );
};
Coding Round
55. Bubble sort

Bubble sort with early termination optimization.

  • Algorithm: Compare adjacent, swap
  • Time: O(n²) worst case
  • Optimization: Stop if no swaps
  • In-place: Modifies original array
typescript
// Bubble sort in React Native
const bubbleSort = (arr) => {
  const sorted = [...arr];
  for (let i = 0; i < sorted.length - 1; i++) {
    for (let j = 0; j < sorted.length - 1 - i; j++) {
      if (sorted[j] > sorted[j + 1]) {
        [sorted[j], sorted[j + 1]] = [sorted[j + 1], sorted[j]];
      }
    }
  }
  return sorted;
};

// Optimized bubble sort
const bubbleSortOptimized = (arr) => {
  const sorted = [...arr];
  for (let i = 0; i < sorted.length - 1; i++) {
    let swapped = false;
    for (let j = 0; j < sorted.length - 1 - i; j++) {
      if (sorted[j] > sorted[j + 1]) {
        [sorted[j], sorted[j + 1]] = [sorted[j + 1], sorted[j]];
        swapped = true;
      }
    }
    if (!swapped) break;
  }
  return sorted;
};

// Usage in component
const App = () => {
  const numbers = [5, 3, 8, 4, 2, 7, 1, 6];
  const sorted = bubbleSort(numbers);
  
  return (
    <View>
      <Text>Original: {numbers.join(', ')}</Text>
      <Text>Sorted: {sorted.join(', ')}</Text>
    </View>
  );
};
Coding Round
56. Intersection of arrays

Find common elements using Set or filter.

  • Set: new Set(arr2) and filter
  • filter: arr1.filter(item => arr2.includes(item))
  • reduce: Accumulate common elements
  • Complexity: O(n) time with Set
typescript
// Intersection of arrays in React Native
const intersection = (arr1, arr2) => {
  const set2 = new Set(arr2);
  return arr1.filter(item => set2.has(item));
};

// Using filter and includes
const intersectionFilter = (arr1, arr2) => {
  return arr1.filter(item => arr2.includes(item));
};

// Usage in component
const App = () => {
  const arr1 = [1, 2, 3, 4];
  const arr2 = [3, 4, 5, 6];
  const result = intersection(arr1, arr2);
  
  return (
    <View>
      <Text>Array1: {arr1.join(', ')}</Text>
      <Text>Array2: {arr2.join(', ')}</Text>
      <Text>Intersection: {result.join(', ')}</Text>
    </View>
  );
};
Coding Round
57. Union of arrays

Combine arrays with unique elements using Set.

  • Set: [...new Set([...arr1, ...arr2])]
  • concat: arr1.concat(arr2) then Set
  • Preserve order: Set preserves insertion order
  • Complexity: O(n) time
typescript
// Union of arrays in React Native
const union = (arr1, arr2) => {
  return [...new Set([...arr1, ...arr2])];
};

// Preserving order
const unionOrder = (arr1, arr2) => {
  const result = [...arr1];
  for (const item of arr2) {
    if (!result.includes(item)) {
      result.push(item);
    }
  }
  return result;
};

// Usage in component
const App = () => {
  const arr1 = [1, 2, 3];
  const arr2 = [3, 4, 5];
  const result = union(arr1, arr2);
  
  return (
    <View>
      <Text>Array1: {arr1.join(', ')}</Text>
      <Text>Array2: {arr2.join(', ')}</Text>
      <Text>Union: {result.join(', ')}</Text>
    </View>
  );
};
Coding Round
58. Difference of arrays

Find elements in first array not in second using Set.

  • Set: new Set(arr2) and filter
  • filter: arr1.filter(item => !arr2.includes(item))
  • Symmetric difference: Union of differences
  • Complexity: O(n) time
typescript
// Difference of arrays in React Native
const difference = (arr1, arr2) => {
  const set2 = new Set(arr2);
  return arr1.filter(item => !set2.has(item));
};

// Symmetric difference
const symmetricDifference = (arr1, arr2) => {
  const set1 = new Set(arr1);
  const set2 = new Set(arr2);
  const result = [];
  for (const item of set1) {
    if (!set2.has(item)) result.push(item);
  }
  for (const item of set2) {
    if (!set1.has(item)) result.push(item);
  }
  return result;
};

// Usage in component
const App = () => {
  const arr1 = [1, 2, 3, 4];
  const arr2 = [3, 4, 5, 6];
  const diff = difference(arr1, arr2);
  
  return (
    <View>
      <Text>Array1: {arr1.join(', ')}</Text>
      <Text>Array2: {arr2.join(', ')}</Text>
      <Text>Difference: {diff.join(', ')}</Text>
    </View>
  );
};
Coding Round
59. Group by property

Group objects by property using reduce or for loop.

  • reduce: Accumulate into object
  • for loop: Manual grouping
  • Key: Property value as key
  • Complexity: O(n) time
typescript
// Group by property in React Native
const groupByProperty = (items, key) => {
  const groups = {};
  for (const item of items) {
    const keyValue = item[key];
    if (!groups[keyValue]) {
      groups[keyValue] = [];
    }
    groups[keyValue].push(item);
  }
  return groups;
};

// Using reduce
const groupByPropertyReduce = (items, key) => {
  return items.reduce((groups, item) => {
    const keyValue = item[key];
    if (!groups[keyValue]) {
      groups[keyValue] = [];
    }
    groups[keyValue].push(item);
    return groups;
  }, {});
};

// Usage in component
const App = () => {
  const data = [
    { type: 'fruit', name: 'apple' },
    { type: 'fruit', name: 'banana' },
    { type: 'veg', name: 'carrot' }
  ];
  const groups = groupByProperty(data, 'type');
  
  return (
    <View>
      {Object.entries(groups).map(([key, items]) => (
        <View key={key}>
          <Text style={{fontWeight: 'bold'}}>{key}:</Text>
          {items.map((item, index) => (
            <Text key={index}>  - {item.name}</Text>
          ))}
        </View>
      ))}
    </View>
  );
};
Coding Round
60. Deep clone object

Deep clone using recursion or JSON methods.

  • JSON: JSON.parse(JSON.stringify(obj))
  • Recursive: Copy nested structures
  • Spread: {...obj} (shallow)
  • Object.assign: Object.assign({}, obj) (shallow)
typescript
// Deep clone object in React Native
const deepClone = (obj) => {
  if (obj === null || typeof obj !== 'object') return obj;
  if (Array.isArray(obj)) {
    return obj.map(item => deepClone(item));
  }
  const cloned = {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      cloned[key] = deepClone(obj[key]);
    }
  }
  return cloned;
};

// Using JSON methods
const deepCloneJSON = (obj) => {
  return JSON.parse(JSON.stringify(obj));
};

// Usage in component
const App = () => {
  const original = {
    name: 'Alice',
    address: { city: 'NYC', zip: '10001' }
  };
  const cloned = deepClone(original);
  cloned.name = 'Bob';
  cloned.address.city = 'LA';
  
  return (
    <View>
      <Text>Original: {JSON.stringify(original)}</Text>
      <Text>Cloned: {JSON.stringify(cloned)}</Text>
    </View>
  );
};
Coding Round
61. Immutable update

Perform immutable updates using spread or Object.assign.

  • Spread: {...obj, [key]: value}
  • Object.assign: Object.assign({}, obj, {[key]: value})
  • Nested: Recursive spread updates
  • Return: New immutable object
typescript
// Immutable update in React Native
const updateImmutable = (obj, path, value) => {
  const parts = path.split('.');
  if (parts.length === 1) {
    return { ...obj, [parts[0]]: value };
  }
  const first = parts[0];
  const rest = parts.slice(1).join('.');
  const nested = obj[first] || {};
  return { ...obj, [first]: updateImmutable(nested, rest, value) };
};

// Usage in component
const App = () => {
  const [state, setState] = useState({
    user: { name: 'Alice', age: 25 }
  });
  
  const handleUpdate = () => {
    const newState = updateImmutable(state, 'user.age', 26);
    setState(newState);
  };
  
  return (
    <View>
      <Text>Name: {state.user.name}</Text>
      <Text>Age: {state.user.age}</Text>
      <Button title="Update Age" onPress={handleUpdate} />
    </View>
  );
};
Coding Round
62. Pipe function

Pipe composes functions from left to right.

  • Implementation: fns.reduce((acc, fn) => fn(acc), value)
  • Variadic: Accept multiple functions
  • Return: Function that chains operations
  • Direction: Left to right
typescript
// Pipe function in React Native
const pipe = (...fns) => {
  return (value) => {
    return fns.reduce((acc, fn) => fn(acc), value);
  };
};

// Usage in component
const App = () => {
  const double = (x) => x * 2;
  const addTen = (x) => x + 10;
  const square = (x) => x * x;
  
  const process = pipe(double, addTen, square);
  const result = process(5);
  
  return (
    <View>
      <Text>Input: 5</Text>
      <Text>Result: {result}</Text>
    </View>
  );
};
Coding Round
63. Compose function

Compose functions from right to left.

  • Implementation: fns.reduceRight((acc, fn) => fn(acc), value)
  • Variadic: Accept multiple functions
  • Return: Function that chains operations
  • Direction: Right to left
typescript
// Compose function in React Native
const compose = (...fns) => {
  return (value) => {
    return fns.reduceRight((acc, fn) => fn(acc), value);
  };
};

// Usage in component
const App = () => {
  const double = (x) => x * 2;
  const addTen = (x) => x + 10;
  const square = (x) => x * x;
  
  const process = compose(square, addTen, double);
  const result = process(5);
  
  return (
    <View>
      <Text>Input: 5</Text>
      <Text>Result: {result}</Text>
    </View>
  );
};
Coding Round
64. Memoization

Cache function results based on arguments using object.

  • Cache: or Map
  • Key: JSON.stringify(args)
  • Return: Cached or computed result
  • Trade-off: Memory for speed
typescript
// Memoization in React Native
const memoize = (fn) => {
  const cache = {};
  return (arg) => {
    const key = JSON.stringify(arg);
    if (cache.hasOwnProperty(key)) {
      return cache[key];
    }
    const result = fn(arg);
    cache[key] = result;
    return result;
  };
};

// Fibonacci with memoization
const fibMemo = memoize((n) => {
  if (n <= 1) return n;
  return fibMemo(n - 1) + fibMemo(n - 2);
});

// Usage in component
const App = () => {
  const [n, setN] = useState(10);
  const result = fibMemo(n);
  
  return (
    <View>
      <Text>Fibonacci({n}) = {result}</Text>
      <Button title="Next" onPress={() => setN(n + 1)} />
    </View>
  );
};
Coding Round
65. Once function

Ensure a function is called only once using closure.

  • Closure: let called = false
  • Result: Cache the result
  • Return: Function with guard
  • Use case: Initialization
typescript
// Once function in React Native
const once = (fn) => {
  let called = false;
  let result = null;
  return (...args) => {
    if (!called) {
      called = true;
      result = fn(...args);
    }
    return result;
  };
};

// Usage in component
const App = () => {
  const [message, setMessage] = useState('');
  
  const initialize = once(() => {
    console.log('Initialized');
    return { id: 1, name: 'App' };
  });
  
  const handleInit = () => {
    const result = initialize();
    setMessage(JSON.stringify(result));
  };
  
  return (
    <View>
      <Text>{message}</Text>
      <Button title="Initialize" onPress={handleInit} />
      <Button title="Initialize Again" onPress={handleInit} />
    </View>
  );
};
Coding Round
66. Debounce with leading edge

Debounce with leading edge using timer and timestamp.

  • Timer: setTimeout for delayed execution
  • Leading edge: Execute immediately
  • Cooldown: Wait before next execution
  • Use case: Search input, API calls
typescript
// Debounce with leading edge in React Native
const debounceLeading = (delayMs, fn) => {
  let lastCall = 0;
  let timer = null;
  return (...args) => {
    const now = Date.now();
    if (now - lastCall < delayMs) {
      if (timer) clearTimeout(timer);
      timer = setTimeout(() => {
        lastCall = Date.now();
        fn(...args);
      }, delayMs);
    } else {
      lastCall = now;
      fn(...args);
    }
  };
};

// Usage in component
const App = () => {
  const [search, setSearch] = useState('');
  
  const handleSearch = debounceLeading(500, (text) => {
    console.log('Searching:', text);
  });
  
  return (
    <View>
      <TextInput
        value={search}
        onChangeText={(text) => {
          setSearch(text);
          handleSearch(text);
        }}
        placeholder="Search..."
      />
    </View>
  );
};
Coding Round
67. Throttle with leading edge

Throttle with leading edge using timestamp tracking.

  • Timestamp: Track last execution time
  • Leading edge: Execute if enough time passed
  • Rate limiting: At most once per period
  • Use case: Scroll events, resize
typescript
// Throttle with leading edge in React Native
const throttleLeading = (delayMs, fn) => {
  let lastCall = 0;
  return (...args) => {
    const now = Date.now();
    if (now - lastCall >= delayMs) {
      lastCall = now;
      fn(...args);
    }
  };
};

// Usage in component
const App = () => {
  const [scrollPosition, setScrollPosition] = useState(0);
  
  const handleScroll = throttleLeading(200, (event) => {
    const y = event.nativeEvent.contentOffset.y;
    setScrollPosition(y);
  });
  
  return (
    <ScrollView onScroll={handleScroll}>
      <Text>Scroll Position: {scrollPosition}</Text>
      {Array.from({length: 20}, (_, i) => (
        <Text key={i}>Item {i + 1}</Text>
      ))}
    </ScrollView>
  );
};
Coding Round
68. Deep equal

Deep equality comparison using recursion for nested structures.

  • Recursive: Compare nested structures
  • Base cases: Primitive values
  • Arrays: Compare elements recursively
  • Objects: Compare key-value pairs
typescript
// Deep equal in React Native
const deepEqual = (obj1, obj2) => {
  if (obj1 === obj2) return true;
  if (obj1 === null || obj2 === null) return false;
  if (typeof obj1 !== 'object' || typeof obj2 !== 'object') return false;
  if (Array.isArray(obj1) !== Array.isArray(obj2)) return false;
  
  if (Array.isArray(obj1)) {
    if (obj1.length !== obj2.length) return false;
    for (let i = 0; i < obj1.length; i++) {
      if (!deepEqual(obj1[i], obj2[i])) return false;
    }
    return true;
  }
  
  const keys1 = Object.keys(obj1);
  const keys2 = Object.keys(obj2);
  if (keys1.length !== keys2.length) return false;
  
  for (const key of keys1) {
    if (!obj2.hasOwnProperty(key)) return false;
    if (!deepEqual(obj1[key], obj2[key])) return false;
  }
  return true;
};

// Usage in component
const App = () => {
  const obj1 = { name: 'Alice', address: { city: 'NYC' } };
  const obj2 = { name: 'Alice', address: { city: 'NYC' } };
  const obj3 = { name: 'Bob', address: { city: 'LA' } };
  
  return (
    <View>
      <Text>obj1 === obj2: {deepEqual(obj1, obj2) ? 'Yes' : 'No'}</Text>
      <Text>obj1 === obj3: {deepEqual(obj1, obj3) ? 'Yes' : 'No'}</Text>
    </View>
  );
};
Coding Round
69. Observable pattern

Observable pattern with subscribers and notifications.

  • Observable: Maintains subscribers
  • Subscribe: Add callback
  • Notify: Call all subscribers
  • Unsubscribe: Remove callback
typescript
// Observable pattern in React Native
class Observable {
  constructor() {
    this.subscribers = [];
  }
  
  subscribe(callback) {
    this.subscribers.push(callback);
    return () => {
      this.subscribers = this.subscribers.filter(cb => cb !== callback);
    };
  }
  
  notify(data) {
    this.subscribers.forEach(callback => callback(data));
  }
}

// Usage in component
const App = () => {
  const [messages, setMessages] = useState([]);
  const observable = new Observable();
  
  useEffect(() => {
    const unsubscribe = observable.subscribe((data) => {
      setMessages(prev => [...prev, data]);
    });
    return unsubscribe;
  }, []);
  
  const handleNotify = () => {
    observable.notify(`Message ${messages.length + 1}`);
  };
  
  return (
    <View>
      <FlatList
        data={messages}
        renderItem={({item}) => <Text>{item}</Text>}
        keyExtractor={(item, index) => index.toString()}
      />
      <Button title="Send Message" onPress={handleNotify} />
    </View>
  );
};
Coding Round
70. Singleton pattern

Singleton pattern using closure or class with static instance.

  • Closure: IIFE with private instance
  • Class: Static getInstance method
  • Lazy initialization: Create on first access
  • Global access: Through shared instance
typescript
// Singleton pattern in React Native
class Singleton {
  constructor() {
    if (Singleton.instance) {
      return Singleton.instance;
    }
    this.data = {};
    Singleton.instance = this;
  }
  
  set(key, value) {
    this.data[key] = value;
  }
  
  get(key) {
    return this.data[key];
  }
}

// Usage in component
const App = () => {
  const [value, setValue] = useState('');
  
  const handleSet = () => {
    const singleton = new Singleton();
    singleton.set('name', 'Alice');
    setValue('Set name to Alice');
  };
  
  const handleGet = () => {
    const singleton = new Singleton();
    const name = singleton.get('name');
    setValue(`Retrieved name: ${name}`);
  };
  
  return (
    <View>
      <Text>{value}</Text>
      <Button title="Set" onPress={handleSet} />
      <Button title="Get" onPress={handleGet} />
    </View>
  );
};
Coding Round
71. Factory pattern

Factory pattern using functions that create objects.

  • Factory function: Creates objects
  • Type parameter: Determines which class
  • Return: Instance of requested type
  • Benefits: Decouples creation logic
typescript
// Factory pattern in React Native
const createUser = (type, name) => {
  switch(type) {
    case 'admin':
      return { role: 'admin', name, permissions: ['read', 'write'] };
    case 'guest':
      return { role: 'guest', name, permissions: ['read'] };
    default:
      return { role: 'user', name, permissions: ['read'] };
  }
};

// Usage in component
const App = () => {
  const admin = createUser('admin', 'Alice');
  const guest = createUser('guest', 'Bob');
  
  return (
    <View>
      <Text>Admin: {admin.name}, Role: {admin.role}</Text>
      <Text>Guest: {guest.name}, Role: {guest.role}</Text>
    </View>
  );
};
Coding Round
72. Strategy pattern

Strategy pattern using functions or objects with algorithms.

  • Strategy functions: Different algorithms
  • Context: Uses strategy
  • Runtime switching: Change at runtime
  • Benefits: Encapsulate algorithms
typescript
// Strategy pattern in React Native
const strategies = {
  credit: (amount) => `Paid $${amount} with Credit Card`,
  paypal: (amount) => `Paid $${amount} with PayPal`,
  crypto: (amount) => `Paid $${amount} with Crypto`
};

const PaymentContext = (strategy) => {
  return (amount) => strategies[strategy](amount);
};

// Usage in component
const App = () => {
  const [result, setResult] = useState('');
  
  const handlePayment = (strategy) => {
    const pay = PaymentContext(strategy);
    setResult(pay(100));
  };
  
  return (
    <View>
      <Text>{result}</Text>
      <Button title="Credit Card" onPress={() => handlePayment('credit')} />
      <Button title="PayPal" onPress={() => handlePayment('paypal')} />
      <Button title="Crypto" onPress={() => handlePayment('crypto')} />
    </View>
  );
};
Coding Round
73. Observer pattern

Observer pattern with subject and observers.

  • Subject: Maintains observers
  • Observer: Defines update method
  • Attach/Detach: Add/remove observers
  • Notify: Call update on all observers
typescript
// Observer pattern in React Native
class Subject {
  constructor() {
    this.observers = [];
    this.state = '';
  }
  
  attach(observer) {
    this.observers.push(observer);
  }
  
  detach(observer) {
    this.observers = this.observers.filter(o => o !== observer);
  }
  
  setState(state) {
    this.state = state;
    this.notify();
  }
  
  notify() {
    this.observers.forEach(observer => observer.update(this.state));
  }
}

class Observer {
  constructor(name) {
    this.name = name;
  }
  
  update(data) {
    console.log(`${this.name} received: ${data}`);
  }
}

// Usage in component
const App = () => {
  const [messages, setMessages] = useState([]);
  const subject = new Subject();
  
  useEffect(() => {
    const observer1 = new Observer('Observer1');
    const observer2 = new Observer('Observer2');
    subject.attach(observer1);
    subject.attach(observer2);
    
    subject.setState('Hello World');
  }, []);
  
  return (
    <View>
      <Text>Check console for observer messages</Text>
    </View>
  );
};
Coding Round
74. Decorator pattern

Decorator pattern using wrapper functions or classes.

  • Component: Base object
  • Decorator: Wraps component
  • Chaining: Multiple decorators
  • Benefits: Add behavior dynamically
typescript
// Decorator pattern in React Native
const coffee = () => ({
  cost: 5.0,
  description: 'Coffee'
});

const milkDecorator = (coffee) => ({
  cost: coffee.cost + 2.0,
  description: `${coffee.description}, Milk`
});

const sugarDecorator = (coffee) => ({
  cost: coffee.cost + 1.0,
  description: `${coffee.description}, Sugar`
});

// Usage in component
const App = () => {
  let myCoffee = coffee();
  myCoffee = milkDecorator(myCoffee);
  myCoffee = sugarDecorator(myCoffee);
  
  return (
    <View>
      <Text>Description: {myCoffee.description}</Text>
      <Text>Cost: ${myCoffee.cost}</Text>
    </View>
  );
};
Coding Round
75. Command pattern

Command pattern with execute and undo methods.

  • Command: Execute and undo methods
  • Receiver: Performs actual work
  • Invoker: Executes commands
  • Undo/Redo: Command history
typescript
// Command pattern in React Native
class AddCommand {
  constructor(receiver, value) {
    this.receiver = receiver;
    this.value = value;
  }
  
  execute() {
    this.receiver.push(this.value);
  }
  
  undo() {
    const index = this.receiver.indexOf(this.value);
    if (index !== -1) {
      this.receiver.splice(index, 1);
    }
  }
}

// Usage in component
const App = () => {
  const [items, setItems] = useState([1, 2, 3]);
  const [command, setCommand] = useState(null);
  
  const handleAdd = () => {
    const cmd = new AddCommand(items, 4);
    cmd.execute();
    setItems([...items]);
    setCommand(cmd);
  };
  
  const handleUndo = () => {
    if (command) {
      command.undo();
      setItems([...items]);
    }
  };
  
  return (
    <View>
      <Text>Items: {items.join(', ')}</Text>
      <Button title="Add 4" onPress={handleAdd} />
      <Button title="Undo" onPress={handleUndo} />
    </View>
  );
};
Coding Round
76. Memento pattern

Memento pattern for state capture and restoration.

  • Originator: Creates and restores mementos
  • Memento: Stores state
  • Caretaker: Manages mementos
  • Undo/Redo: State history
typescript
// Memento pattern in React Native
class Memento {
  constructor(state) {
    this.state = state;
  }
}

class Originator {
  constructor() {
    this.state = null;
  }
  
  saveState() {
    return new Memento(JSON.parse(JSON.stringify(this.state)));
  }
  
  restoreState(memento) {
    this.state = memento.state;
  }
}

class Caretaker {
  constructor() {
    this.mementos = [];
  }
  
  addMemento(memento) {
    this.mementos.push(memento);
  }
  
  getMemento(index) {
    return this.mementos[index];
  }
}

// Usage in component
const App = () => {
  const [state, setState] = useState({ name: 'State 1' });
  const originator = new Originator();
  const caretaker = new Caretaker();
  
  const handleSave = () => {
    originator.state = state;
    caretaker.addMemento(originator.saveState());
    setState({ ...state, name: `State ${caretaker.mementos.length + 1}` });
  };
  
  const handleRestore = () => {
    if (caretaker.mementos.length > 0) {
      originator.restoreState(caretaker.getMemento(0));
      setState(originator.state);
    }
  };
  
  return (
    <View>
      <Text>Current State: {state.name}</Text>
      <Button title="Save" onPress={handleSave} />
      <Button title="Restore First" onPress={handleRestore} />
    </View>
  );
};
Coding Round
77. Mediator pattern

Mediator pattern for centralized communication.

  • Mediator: Encapsulates communication
  • Colleague: Communicates through mediator
  • Benefits: Loose coupling
  • Use case: Chat systems
typescript
// Mediator pattern in React Native
class Mediator {
  constructor() {
    this.colleagues = [];
  }
  
  register(colleague) {
    this.colleagues.push(colleague);
    colleague.mediator = this;
  }
  
  send(message, sender) {
    this.colleagues.forEach(colleague => {
      if (colleague !== sender) {
        colleague.receive(message);
      }
    });
  }
}

class Colleague {
  constructor(name) {
    this.name = name;
    this.mediator = null;
  }
  
  send(message) {
    if (this.mediator) {
      this.mediator.send(message, this);
    }
  }
  
  receive(message) {
    console.log(`${this.name} received: ${message}`);
  }
}

// Usage in component
const App = () => {
  useEffect(() => {
    const mediator = new Mediator();
    const alice = new Colleague('Alice');
    const bob = new Colleague('Bob');
    mediator.register(alice);
    mediator.register(bob);
    alice.send('Hello Bob!');
  }, []);
  
  return (
    <View>
      <Text>Check console for mediator messages</Text>
    </View>
  );
};
Coding Round
78. Chain of Responsibility

Chain of Responsibility for processing requests sequentially.

  • Handler: Processes or forwards
  • Chain: Linked list of handlers
  • Benefits: Decoupling
  • Use case: Logging, authentication
typescript
// Chain of Responsibility in React Native
class Handler {
  constructor() {
    this.nextHandler = null;
  }
  
  setNext(handler) {
    this.nextHandler = handler;
    return handler;
  }
  
  handle(request) {
    if (this.nextHandler) {
      return this.nextHandler.handle(request);
    }
    return null;
  }
}

class AuthHandler extends Handler {
  handle(request) {
    if (request.token) {
      console.log('Authentication passed');
      return super.handle(request);
    }
    console.log('Authentication failed');
    return null;
  }
}

class LoggerHandler extends Handler {
  handle(request) {
    console.log(`Logging request: ${request.url}`);
    return super.handle(request);
  }
}

// Usage in component
const App = () => {
  useEffect(() => {
    const auth = new AuthHandler();
    const logger = new LoggerHandler();
    auth.setNext(logger);
    auth.handle({ token: 'valid', url: '/api' });
  }, []);
  
  return (
    <View>
      <Text>Check console for chain messages</Text>
    </View>
  );
};
Coding Round
79. State pattern

State pattern for changing behavior with state.

  • Context: Maintains state
  • State: Defines behavior
  • Transitions: Change between states
  • Benefits: Clean state management
typescript
// State pattern in React Native
class Context {
  constructor() {
    this.state = new ReadyState();
  }
  
  setState(state) {
    this.state = state;
  }
  
  request() {
    this.state.handle(this);
  }
}

class ReadyState {
  handle(context) {
    console.log('Ready: Waiting for input');
    context.setState(new ProcessingState());
  }
}

class ProcessingState {
  handle(context) {
    console.log('Processing: Working on task');
    context.setState(new CompletedState());
  }
}

class CompletedState {
  handle(context) {
    console.log('Completed: Task finished');
  }
}

// Usage in component
const App = () => {
  const [status, setStatus] = useState('Ready');
  const context = new Context();
  
  const handleStep = () => {
    context.request();
    setStatus(context.state.constructor.name.replace('State', ''));
  };
  
  return (
    <View>
      <Text>Status: {status}</Text>
      <Button title="Next Step" onPress={handleStep} />
    </View>
  );
};
Coding Round
80. Proxy pattern

Proxy pattern for controlling access to objects.

  • Subject: Real object
  • Proxy: Controls access
  • Lazy loading: Create on demand
  • Benefits: Access control, logging
typescript
// Proxy pattern in React Native
class RealSubject {
  request() {
    console.log('RealSubject: Handling request');
  }
}

class Proxy {
  constructor() {
    this.realSubject = null;
  }
  
  request() {
    if (this.checkAccess()) {
      if (!this.realSubject) {
        this.realSubject = new RealSubject();
      }
      this.realSubject.request();
      this.logAccess();
    }
  }
  
  checkAccess() {
    console.log('Proxy: Checking access');
    return true;
  }
  
  logAccess() {
    console.log('Proxy: Logging access');
  }
}

// Usage in component
const App = () => {
  const proxy = new Proxy();
  
  useEffect(() => {
    proxy.request();
  }, []);
  
  return (
    <View>
      <Text>Check console for proxy messages</Text>
    </View>
  );
};
Coding Round
81. Flyweight pattern

Flyweight pattern for sharing objects to save memory.

  • Flyweight: Shared object
  • Factory: Manages flyweights
  • Benefits: Memory optimization
  • Use case: Character rendering
typescript
// Flyweight pattern in React Native
class Flyweight {
  constructor(sharedState) {
    this.sharedState = sharedState;
  }
  
  operation(uniqueState) {
    console.log(`Shared: ${this.sharedState}, Unique: ${uniqueState}`);
  }
}

class FlyweightFactory {
  constructor() {
    this.flyweights = {};
  }
  
  getFlyweight(sharedState) {
    if (!this.flyweights[sharedState]) {
      this.flyweights[sharedState] = new Flyweight(sharedState);
      console.log(`Creating new flyweight for: ${sharedState}`);
    }
    return this.flyweights[sharedState];
  }
}

// Usage in component
const App = () => {
  const factory = new FlyweightFactory();
  
  useEffect(() => {
    const fw1 = factory.getFlyweight('state1');
    const fw2 = factory.getFlyweight('state1');
    const fw3 = factory.getFlyweight('state2');
    fw1.operation('unique1');
    fw2.operation('unique2');
    fw3.operation('unique3');
  }, []);
  
  return (
    <View>
      <Text>Check console for flyweight messages</Text>
    </View>
  );
};
Coding Round
82. Bridge pattern

Bridge pattern for separating abstraction from implementation.

  • Abstraction: High-level interface
  • Implementation: Low-level operations
  • Benefits: Separation of concerns
  • Use case: Cross-platform
typescript
// Bridge pattern in React Native
class Implementation {
  operationImpl() {}
}

class ConcreteImplementationA extends Implementation {
  operationImpl() {
    console.log('ConcreteImplementationA: Operation');
  }
}

class ConcreteImplementationB extends Implementation {
  operationImpl() {
    console.log('ConcreteImplementationB: Operation');
  }
}

class Abstraction {
  constructor(impl) {
    this.impl = impl;
  }
  
  operation() {
    console.log('Abstraction: Additional logic');
    this.impl.operationImpl();
  }
}

// Usage in component
const App = () => {
  const implA = new ConcreteImplementationA();
  const implB = new ConcreteImplementationB();
  const abstraction1 = new Abstraction(implA);
  const abstraction2 = new Abstraction(implB);
  
  useEffect(() => {
    abstraction1.operation();
    abstraction2.operation();
  }, []);
  
  return (
    <View>
      <Text>Check console for bridge messages</Text>
    </View>
  );
};
Coding Round
83. Adapter pattern

Adapter pattern for converting interfaces.

  • Target: Expected interface
  • Adaptee: Existing interface
  • Adapter: Bridges interfaces
  • Benefits: Reusability
typescript
// Adapter pattern in React Native
class Target {
  request() {
    console.log('Target: Request');
  }
}

class Adaptee {
  specificRequest() {
    console.log('Adaptee: Specific Request');
  }
}

class Adapter extends Target {
  constructor(adaptee) {
    super();
    this.adaptee = adaptee;
  }
  
  request() {
    this.adaptee.specificRequest();
  }
}

// Usage in component
const App = () => {
  const adaptee = new Adaptee();
  const adapter = new Adapter(adaptee);
  
  useEffect(() => {
    adapter.request();
  }, []);
  
  return (
    <View>
      <Text>Check console for adapter messages</Text>
    </View>
  );
};
Coding Round
84. Facade pattern

Facade pattern for simplifying complex subsystems.

  • Facade: Simplified interface
  • Subsystem: Complex components
  • Benefits: Simplified interface
  • Use case: Library APIs
typescript
// Facade pattern in React Native
class SubsystemA {
  operationA() {
    console.log('SubsystemA: Operation');
  }
}

class SubsystemB {
  operationB() {
    console.log('SubsystemB: Operation');
  }
}

class Facade {
  constructor() {
    this.subsystemA = new SubsystemA();
    this.subsystemB = new SubsystemB();
  }
  
  operation() {
    console.log('Facade: Complex operation');
    this.subsystemA.operationA();
    this.subsystemB.operationB();
  }
}

// Usage in component
const App = () => {
  const facade = new Facade();
  
  useEffect(() => {
    facade.operation();
  }, []);
  
  return (
    <View>
      <Text>Check console for facade messages</Text>
    </View>
  );
};
Coding Round
85. Composite pattern

Composite pattern for tree structures.

  • Component: Interface for all
  • Leaf: Individual object
  • Composite: Container
  • Benefits: Uniform interface
typescript
// Composite pattern in React Native
class Leaf {
  constructor(name) {
    this.name = name;
  }
  
  operation() {
    console.log(`Leaf ${this.name}: Operation`);
  }
}

class Composite {
  constructor(name) {
    this.name = name;
    this.children = [];
  }
  
  add(component) {
    this.children.push(component);
  }
  
  remove(component) {
    this.children = this.children.filter(c => c !== component);
  }
  
  operation() {
    console.log(`Composite ${this.name}: Operation`);
    this.children.forEach(child => child.operation());
  }
}

// Usage in component
const App = () => {
  const leaf1 = new Leaf('A');
  const leaf2 = new Leaf('B');
  const composite = new Composite('Root');
  composite.add(leaf1);
  composite.add(leaf2);
  
  useEffect(() => {
    composite.operation();
  }, []);
  
  return (
    <View>
      <Text>Check console for composite messages</Text>
    </View>
  );
};
Coding Round
86. Visitor pattern

Visitor pattern for adding operations without modifying elements.

  • Visitor: Defines operations
  • Element: Accepts visitors
  • Benefits: Adding operations without modifying
  • Use case: Compilers, AST
typescript
// Visitor pattern in React Native
class Visitor {
  visitElementA(element) {}
  visitElementB(element) {}
}

class ElementA {
  accept(visitor) {
    visitor.visitElementA(this);
  }
}

class ElementB {
  accept(visitor) {
    visitor.visitElementB(this);
  }
}

class ConcreteVisitor extends Visitor {
  visitElementA(element) {
    console.log('Visiting ElementA');
  }
  
  visitElementB(element) {
    console.log('Visiting ElementB');
  }
}

// Usage in component
const App = () => {
  const visitor = new ConcreteVisitor();
  const elementA = new ElementA();
  const elementB = new ElementB();
  
  useEffect(() => {
    elementA.accept(visitor);
    elementB.accept(visitor);
  }, []);
  
  return (
    <View>
      <Text>Check console for visitor messages</Text>
    </View>
  );
};
Coding Round
87. Iterator pattern

Iterator pattern for sequential access to collections.

  • Iterator: Traverses collection
  • Aggregate: Creates iterator
  • Benefits: Uniform traversal
  • Use case: Collection traversal
typescript
// Iterator pattern in React Native
class Iterator {
  constructor(collection) {
    this.collection = collection;
    this.index = 0;
  }
  
  next() {
    if (this.hasNext()) {
      return this.collection[this.index++];
    }
    return null;
  }
  
  hasNext() {
    return this.index < this.collection.length;
  }
}

class CustomCollection {
  constructor() {
    this.items = [];
  }
  
  add(item) {
    this.items.push(item);
  }
  
  getIterator() {
    return new Iterator(this.items);
  }
}

// Usage in component
const App = () => {
  const [items, setItems] = useState([]);
  const collection = new CustomCollection();
  
  useEffect(() => {
    collection.add('A');
    collection.add('B');
    collection.add('C');
    const iterator = collection.getIterator();
    const result = [];
    while (iterator.hasNext()) {
      result.push(iterator.next());
    }
    setItems(result);
  }, []);
  
  return (
    <View>
      {items.map((item, index) => (
        <Text key={index}>{item}</Text>
      ))}
    </View>
  );
};
Coding Round
88. Template Method pattern

Template Method for algorithm skeletons.

  • AbstractClass: Defines template
  • ConcreteClass: Implements steps
  • Benefits: Code reuse
  • Use case: Frameworks
typescript
// Template Method pattern in React Native
class AbstractClass {
  templateMethod() {
    this.step1();
    this.step2();
    this.step3();
  }
  
  step1() {
    console.log('Step 1');
  }
  
  step2() {}
  
  step3() {
    console.log('Step 3');
  }
}

class ConcreteClass extends AbstractClass {
  step2() {
    console.log('Concrete Step 2');
  }
}

// Usage in component
const App = () => {
  const concrete = new ConcreteClass();
  
  useEffect(() => {
    concrete.templateMethod();
  }, []);
  
  return (
    <View>
      <Text>Check console for template method messages</Text>
    </View>
  );
};
Coding Round
89. Builder pattern

Builder pattern for constructing complex objects.

  • Builder: Constructs parts
  • Director: Orchestrates construction
  • Product: Constructed object
  • Benefits: Step-by-step construction
typescript
// Builder pattern in React Native
class Product {
  constructor() {
    this.parts = [];
  }
  
  add(part) {
    this.parts.push(part);
  }
  
  listParts() {
    console.log(this.parts.join(', '));
  }
}

class Builder {
  constructor() {
    this.reset();
  }
  
  reset() {
    this.product = new Product();
  }
  
  buildStepA() {
    this.product.add('Part A');
  }
  
  buildStepB() {
    this.product.add('Part B');
  }
  
  getResult() {
    return this.product;
  }
}

class Director {
  constructor(builder) {
    this.builder = builder;
  }
  
  buildMinimal() {
    this.builder.buildStepA();
  }
  
  buildFull() {
    this.builder.buildStepA();
    this.builder.buildStepB();
  }
}

// Usage in component
const App = () => {
  const builder = new Builder();
  const director = new Director(builder);
  director.buildMinimal();
  const product = builder.getResult();
  
  return (
    <View>
      <Text>Product parts: {product.parts.join(', ')}</Text>
    </View>
  );
};
Coding Round
90. Prototype pattern

Prototype pattern for cloning objects using copy methods.

  • Clone method: Creates a copy
  • Shallow copy: Object.assign()
  • Deep copy: Recursive copy or JSON
  • Benefits: Object reuse, performance
typescript
// Prototype pattern in React Native
class Prototype {
  constructor(name, nested) {
    this.name = name;
    this.nested = nested || {};
  }
  
  clone() {
    return new Prototype(this.name, { ...this.nested });
  }
  
  deepClone() {
    return new Prototype(
      this.name,
      JSON.parse(JSON.stringify(this.nested))
    );
  }
}

// Usage in component
const App = () => {
  const original = new Prototype('Original', { value: 42 });
  const copy = original.clone();
  copy.name = 'Copy';
  copy.nested.value = 99;
  
  const deepCopy = original.deepClone();
  deepCopy.nested.value = 100;
  
  return (
    <View>
      <Text>Original name: {original.name}</Text>
      <Text>Original nested value: {original.nested.value}</Text>
      <Text>Copy name: {copy.name}</Text>
      <Text>DeepCopy nested value: {deepCopy.nested.value}</Text>
    </View>
  );
};
Coding Round
91. Async Storage in React Native

AsyncStorage is a key-value storage system for React Native apps, used for persisting data locally.

  • Set: await AsyncStorage.setItem('key', 'value')
  • Get: await AsyncStorage.getItem('key')
  • Remove: await AsyncStorage.removeItem('key')
  • Clear: await AsyncStorage.clear()
  • Multi operations: multiGet, multiSet
typescript
// Async Storage in React Native
import AsyncStorage from '@react-native-async-storage/async-storage';

const App = () => {
  const [data, setData] = useState('');
  const [loading, setLoading] = useState(false);
  
  const saveData = async (key, value) => {
    try {
      await AsyncStorage.setItem(key, value);
      console.log('Data saved successfully');
    } catch (error) {
      console.error('Error saving data:', error);
    }
  };
  
  const loadData = async (key) => {
    try {
      setLoading(true);
      const value = await AsyncStorage.getItem(key);
      setData(value || 'No data found');
    } catch (error) {
      console.error('Error loading data:', error);
    } finally {
      setLoading(false);
    }
  };
  
  const removeData = async (key) => {
    try {
      await AsyncStorage.removeItem(key);
      setData('Data removed');
    } catch (error) {
      console.error('Error removing data:', error);
    }
  };
  
  return (
    <View>
      {loading && <ActivityIndicator size="large" />}
      <Text>Data: {data}</Text>
      <Button title="Save Data" onPress={() => saveData('user', 'Alice')} />
      <Button title="Load Data" onPress={() => loadData('user')} />
      <Button title="Remove Data" onPress={() => removeData('user')} />
    </View>
  );
};
Coding Round
92. Networking in React Native

Networking in React Native uses fetch or axios for HTTP requests with async/await and error handling.

  • GET: fetch(url).then(res => res.json())
  • POST: fetch(url, { method: 'POST', body: JSON.stringify(data) })
  • Headers: { headers: { 'Content-Type': 'application/json' } }
  • Error handling: try { } catch (error) { }
  • Abort: AbortController for canceling requests
typescript
// Networking in React Native
const App = () => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  
  const fetchData = async () => {
    try {
      setLoading(true);
      setError(null);
      
      const response = await fetch('https://jsonplaceholder.typicode.com/users');
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const json = await response.json();
      setData(json);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };
  
  const postData = async () => {
    try {
      setLoading(true);
      setError(null);
      
      const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          title: 'Test Post',
          body: 'This is a test post',
          userId: 1,
        }),
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const json = await response.json();
      Alert.alert('Success', 'Post created: ' + json.id);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };
  
  return (
    <View>
      {loading && <ActivityIndicator size="large" />}
      {error && <Text style={{color: 'red'}}>Error: {error}</Text>}
      
      {data && (
        <FlatList
          data={data}
          renderItem={({item}) => (
            <View style={styles.item}>
              <Text style={styles.name}>{item.name}</Text>
              <Text style={styles.email}>{item.email}</Text>
            </View>
          )}
          keyExtractor={item => item.id.toString()}
        />
      )}
      
      <Button title="Fetch Data" onPress={fetchData} />
      <Button title="Post Data" onPress={postData} />
    </View>
  );
};

const styles = StyleSheet.create({
  item: { padding: 10, borderBottomWidth: 1, borderBottomColor: '#ccc' },
  name: { fontSize: 16, fontWeight: 'bold' },
  email: { fontSize: 14, color: '#666' }
});
Coding Round
93. Image Handling in React Native

Image handling in React Native uses the Image component with network, local, and base64 image sources.

  • Network: source={{ uri: 'https://example.com/image.jpg' }}
  • Local: source={require('./image.png')}
  • Base64: source={{ uri: 'data:image/png;base64,...' }}
  • Resize modes: resizeMode: 'cover' | 'contain' | 'stretch'
  • ImageBackground: Component with background image
typescript
// Image Handling in React Native
import { Image, ImageBackground } from 'react-native';

const App = () => {
  const [imageUri, setImageUri] = useState(null);
  
  const pickImage = async () => {
    const result = await ImagePicker.launchImageLibrary({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      quality: 1,
    });
    
    if (!result.canceled) {
      setImageUri(result.assets[0].uri);
    }
  };
  
  return (
    <View style={styles.container}>
      {/* Network image */}
      <Image
        source={{ uri: 'https://via.placeholder.com/150' }}
        style={styles.image}
        resizeMode="cover"
      />
      
      {/* Local image */}
      <Image
        source={require('./assets/logo.png')}
        style={styles.image}
        resizeMode="contain"
      />
      
      {/* Image with loading indicator */}
      <Image
        source={{ uri: 'https://via.placeholder.com/300' }}
        style={styles.image}
        onLoadStart={() => console.log('Loading started')}
        onLoadEnd={() => console.log('Loading ended')}
        onError={(error) => console.log('Error loading image', error)}
      />
      
      {/* ImageBackground */}
      <ImageBackground
        source={{ uri: 'https://via.placeholder.com/200' }}
        style={styles.imageBackground}
        resizeMode="cover"
      >
        <Text style={styles.backgroundText}>Background Image</Text>
      </ImageBackground>
      
      {/* Button to pick image */}
      <Button title="Pick Image" onPress={pickImage} />
      {imageUri && (
        <Image source={{ uri: imageUri }} style={styles.image} />
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20, alignItems: 'center' },
  image: { width: 150, height: 150, marginVertical: 10, borderRadius: 10 },
  imageBackground: { width: 200, height: 100, justifyContent: 'center', alignItems: 'center' },
  backgroundText: { color: 'white', fontWeight: 'bold', fontSize: 16 }
});
Coding Round
94. Animations in React Native

Animations in React Native are implemented using Animated API for smooth, declarative animations.

  • Animated.Value: Animated values
  • Animated.timing: Time-based animations
  • Animated.spring: Spring animations
  • Animated.decay: Decay animations
  • Interpolation: interpolate() for value mapping
typescript
// Animations in React Native
import { Animated, Easing } from 'react-native';

const App = () => {
  const fadeAnim = new Animated.Value(0);
  const scaleAnim = new Animated.Value(0);
  const rotateAnim = new Animated.Value(0);
  const translateYAnim = new Animated.Value(0);
  
  useEffect(() => {
    Animated.parallel([
      Animated.timing(fadeAnim, {
        toValue: 1,
        duration: 2000,
        useNativeDriver: true,
        easing: Easing.ease,
      }),
      Animated.spring(scaleAnim, {
        toValue: 1,
        friction: 1,
        tension: 1,
        useNativeDriver: true,
      }),
      Animated.timing(rotateAnim, {
        toValue: 1,
        duration: 3000,
        useNativeDriver: true,
        easing: Easing.linear,
      }),
      Animated.spring(translateYAnim, {
        toValue: 1,
        useNativeDriver: true,
      }),
    ]).start();
  }, []);
  
  const rotate = rotateAnim.interpolate({
    inputRange: [0, 1],
    outputRange: ['0deg', '360deg'],
  });
  
  const translateY = translateYAnim.interpolate({
    inputRange: [0, 1],
    outputRange: [0, -100],
  });
  
  return (
    <View style={styles.container}>
      <Animated.View
        style={[
          styles.box,
          {
            opacity: fadeAnim,
            transform: [
              { scale: scaleAnim },
              { rotate: rotate },
              { translateY: translateY },
            ],
          },
        ]}
      >
        <Text style={styles.text}>Animated Box</Text>
      </Animated.View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  box: { width: 100, height: 100, backgroundColor: '#007AFF', justifyContent: 'center', alignItems: 'center' },
  text: { color: 'white', fontWeight: 'bold' }
});
Coding Round
95. Gestures in React Native

Gestures in React Native use PanResponder or React Native Gesture Handler for touch interactions.

  • PanResponder: Gesture handling
  • TouchableOpacity: Tap handling
  • TouchableHighlight: Highlight on tap
  • Gesture Handler: Advanced gestures
  • Pinch, Pan, Rotate: Multi-touch gestures
typescript
// Gestures in React Native
import { PanResponder, TouchableOpacity } from 'react-native';

const App = () => {
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const [isPressed, setIsPressed] = useState(false);
  const panResponder = React.useRef(
    PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderMove: (evt, gestureState) => {
        setPosition({
          x: gestureState.dx,
          y: gestureState.dy,
        });
      },
      onPanResponderRelease: () => {
        setPosition({ x: 0, y: 0 });
      },
    })
  ).current;
  
  return (
    <View style={styles.container}>
      <View
        style={[styles.dragArea, { transform: [{ translateX: position.x }, { translateY: position.y }] }]}
        {...panResponder.panHandlers}
      >
        <Text style={styles.dragText}>Drag Me</Text>
      </View>
      
      <TouchableOpacity
        style={[styles.button, isPressed && styles.buttonPressed]}
        onPressIn={() => setIsPressed(true)}
        onPressOut={() => setIsPressed(false)}
        onPress={() => Alert.alert('Pressed', 'Button was pressed!')}
      >
        <Text style={styles.buttonText}>Press Me</Text>
      </TouchableOpacity>
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  dragArea: { width: 100, height: 100, backgroundColor: '#007AFF', justifyContent: 'center', alignItems: 'center', borderRadius: 10 },
  dragText: { color: 'white', fontWeight: 'bold' },
  button: { padding: 15, backgroundColor: '#007AFF', borderRadius: 5, marginTop: 20 },
  buttonPressed: { backgroundColor: '#0055BB', transform: [{ scale: 0.95 }] },
  buttonText: { color: 'white', fontWeight: 'bold' }
});
Coding Round
96. Push Notifications in React Native

Push notifications in React Native are implemented using Firebase Cloud Messaging (FCM) for Android and APNs for iOS.

  • FCM: Android push notifications
  • APNs: iOS push notifications
  • react-native-push-notification: Library
  • @react-native-firebase/messaging: Firebase messaging
  • Handling: Foreground and background handlers
typescript
// Push Notifications in React Native
import messaging from '@react-native-firebase/messaging';

const App = () => {
  const [token, setToken] = useState('');
  const [notification, setNotification] = useState(null);
  
  useEffect(() => {
    const requestPermission = async () => {
      const authStatus = await messaging().requestPermission();
      const enabled =
        authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
        authStatus === messaging.AuthorizationStatus.PROVISIONAL;
      
      if (enabled) {
        console.log('Authorization status:', authStatus);
        getFCMToken();
      }
    };
    
    const getFCMToken = async () => {
      const fcmToken = await messaging().getToken();
      if (fcmToken) {
        console.log('FCM Token:', fcmToken);
        setToken(fcmToken);
      }
    };
    
    // Foreground message handler
    const unsubscribe = messaging().onMessage(async (remoteMessage) => {
      console.log('Message received in foreground:', remoteMessage);
      setNotification(remoteMessage.notification);
      Alert.alert(
        remoteMessage.notification.title,
        remoteMessage.notification.body
      );
    });
    
    // Background message handler
    messaging().setBackgroundMessageHandler(async (remoteMessage) => {
      console.log('Message received in background:', remoteMessage);
    });
    
    requestPermission();
    
    return unsubscribe;
  }, []);
  
  return (
    <View style={styles.container}>
      <Text style={styles.title}>Push Notifications</Text>
      <Text style={styles.text}>FCM Token:</Text>
      <Text style={styles.token}>{token}</Text>
      
      {notification && (
        <View style={styles.notification}>
          <Text style={styles.notificationTitle}>
            {notification.title}
          </Text>
          <Text style={styles.notificationBody}>
            {notification.body}
          </Text>
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20 },
  title: { fontSize: 24, fontWeight: 'bold', marginBottom: 20 },
  text: { fontSize: 16, fontWeight: 'bold', marginTop: 10 },
  token: { fontSize: 14, color: '#666', marginTop: 5 },
  notification: { padding: 15, backgroundColor: '#f0f0f0', borderRadius: 5, marginTop: 20 },
  notificationTitle: { fontSize: 16, fontWeight: 'bold' },
  notificationBody: { fontSize: 14, marginTop: 5 }
});
Coding Round
97. Permissions in React Native

Permissions in React Native are managed using react-native-permissions library for requesting device permissions.

  • Check: check('permission')
  • Request: request('permission')
  • Permission types: Camera, Location, Storage, Contacts
  • Android: Add permissions in AndroidManifest.xml
  • iOS: Add permissions in Info.plist
typescript
// Permissions in React Native
import { PermissionsAndroid, Platform } from 'react-native';
import { check, request, PERMISSIONS, RESULTS } from 'react-native-permissions';

const App = () => {
  const [permissionStatus, setPermissionStatus] = useState('');
  
  const checkPermission = async () => {
    const permission = Platform.select({
      android: PERMISSIONS.ANDROID.CAMERA,
      ios: PERMISSIONS.IOS.CAMERA,
    });
    
    const result = await check(permission);
    setPermissionStatus(`Permission: ${result}`);
  };
  
  const requestPermission = async () => {
    const permission = Platform.select({
      android: PERMISSIONS.ANDROID.CAMERA,
      ios: PERMISSIONS.IOS.CAMERA,
    });
    
    const result = await request(permission);
    setPermissionStatus(`Permission: ${result}`);
    
    if (result === RESULTS.GRANTED) {
      Alert.alert('Permission Granted', 'Camera permission granted!');
    } else if (result === RESULTS.DENIED) {
      Alert.alert('Permission Denied', 'Camera permission denied');
    } else if (result === RESULTS.BLOCKED) {
      Alert.alert('Permission Blocked', 'Camera permission blocked');
    }
  };
  
  // Android specific
  const requestAndroidPermission = async () => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.CAMERA,
        {
          title: 'Camera Permission',
          message: 'App needs access to your camera.',
          buttonNeutral: 'Ask Me Later',
          buttonNegative: 'Cancel',
          buttonPositive: 'OK',
        }
      );
      
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        setPermissionStatus('Camera permission granted');
        Alert.alert('Success', 'Camera permission granted!');
      } else {
        setPermissionStatus('Camera permission denied');
      }
    } catch (err) {
      console.warn(err);
    }
  };
  
  return (
    <View style={styles.container}>
      <Text style={styles.title}>Permissions</Text>
      <Text style={styles.status}>{permissionStatus}</Text>
      
      <Button title="Check Permission" onPress={checkPermission} />
      <Button title="Request Permission" onPress={requestPermission} />
      {Platform.OS === 'android' && (
        <Button title="Request Android Permission" onPress={requestAndroidPermission} />
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20 },
  title: { fontSize: 24, fontWeight: 'bold', marginBottom: 20 },
  status: { fontSize: 16, marginBottom: 20 }
});
Coding Round
98. Device Features in React Native

Device features in React Native are accessed through various APIs for camera, location, accelerometer, and more.

  • Camera: react-native-camera or react-native-image-picker
  • Location: react-native-geolocation
  • Accelerometer: react-native-sensors
  • Device Info: react-native-device-info
  • Battery: react-native-battery
typescript
// Device Features in React Native
import { Camera } from 'react-native-camera';
import Geolocation from 'react-native-geolocation-service';
import DeviceInfo from 'react-native-device-info';

const App = () => {
  const [location, setLocation] = useState(null);
  const [deviceInfo, setDeviceInfo] = useState({});
  
  useEffect(() => {
    // Get device info
    const info = {
      deviceId: DeviceInfo.getDeviceId(),
      deviceName: DeviceInfo.getDeviceName(),
      brand: DeviceInfo.getBrand(),
      model: DeviceInfo.getModel(),
      systemName: DeviceInfo.getSystemName(),
      systemVersion: DeviceInfo.getSystemVersion(),
      appVersion: DeviceInfo.getVersion(),
      buildNumber: DeviceInfo.getBuildNumber(),
    };
    setDeviceInfo(info);
    
    // Get location
    Geolocation.getCurrentPosition(
      (position) => {
        setLocation(position.coords);
      },
      (error) => {
        console.log('Location error:', error);
      },
      { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
    );
    
    // Watch location
    const watchId = Geolocation.watchPosition(
      (position) => {
        setLocation(position.coords);
      },
      (error) => {
        console.log('Watch error:', error);
      },
      { enableHighAccuracy: true, distanceFilter: 10 }
    );
    
    return () => {
      Geolocation.clearWatch(watchId);
    };
  }, []);
  
  const renderDeviceInfo = () => {
    return Object.entries(deviceInfo).map(([key, value]) => (
      <Text key={key} style={styles.infoText}>
        {key}: {value}
      </Text>
    ));
  };
  
  return (
    <ScrollView style={styles.container}>
      <Text style={styles.title}>Device Features</Text>
      
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>Device Info</Text>
        {renderDeviceInfo()}
      </View>
      
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>Location</Text>
        {location ? (
          <Text style={styles.infoText}>
            Latitude: {location.latitude}, Longitude: {location.longitude}
          </Text>
        ) : (
          <Text style={styles.infoText}>Loading location...</Text>
        )}
      </View>
      
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>Battery</Text>
        <Text style={styles.infoText}>Battery Level: {/* Battery info would go here */}</Text>
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20 },
  title: { fontSize: 24, fontWeight: 'bold', marginBottom: 20 },
  section: { marginBottom: 20, padding: 15, borderWidth: 1, borderRadius: 5 },
  sectionTitle: { fontSize: 18, fontWeight: 'bold', marginBottom: 10 },
  infoText: { fontSize: 14, marginVertical: 2 }
});
Coding Round
99. Debugging in React Native

Debugging in React Native uses Chrome DevTools, React Native Debugger, and console logging for development.

  • Chrome DevTools: Debug JavaScript
  • React Native Debugger: Standalone debugger
  • Console.log: Logging to terminal
  • Breakpoints: In-source debugging
  • React Developer Tools: Component inspection
typescript
// Debugging in React Native
const App = () => {
  const [logs, setLogs] = useState([]);
  
  const logDebug = (message, data) => {
    const timestamp = new Date().toISOString();
    const logEntry = {
      timestamp,
      message,
      data: data || null,
    };
    setLogs(prev => [logEntry, ...prev]);
    console.log(`[${timestamp}] ${message}`, data || '');
  };
  
  const handleAction = () => {
    logDebug('Button pressed', { action: 'test', value: 42 });
  };
  
  return (
    <View style={styles.container}>
      <Text style={styles.title}>Debug Console</Text>
      
      <Button title="Log Action" onPress={handleAction} />
      
      <ScrollView style={styles.logContainer}>
        {logs.map((log, index) => (
          <View key={index} style={styles.logEntry}>
            <Text style={styles.logTimestamp}>{log.timestamp}</Text>
            <Text style={styles.logMessage}>{log.message}</Text>
            {log.data && (
              <Text style={styles.logData}>
                {JSON.stringify(log.data, null, 2)}
              </Text>
            )}
          </View>
        ))}
      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20 },
  title: { fontSize: 24, fontWeight: 'bold', marginBottom: 20 },
  logContainer: { flex: 1, marginTop: 20, borderWidth: 1, borderColor: '#ccc', padding: 10 },
  logEntry: { marginBottom: 10, padding: 5, borderBottomWidth: 1, borderBottomColor: '#eee' },
  logTimestamp: { fontSize: 12, color: '#666' },
  logMessage: { fontSize: 14, fontWeight: 'bold' },
  logData: { fontSize: 12, color: '#333', fontFamily: 'monospace', marginTop: 5 }
});
Coding Round
100. Performance Optimization in React Native

Performance optimization in React Native includes optimizing re-renders, using FlatList, and memory management.

  • useMemo: Memoize expensive calculations
  • useCallback: Memoize functions
  • React.memo: Prevent unnecessary re-renders
  • FlatList: Efficient list rendering
  • useReducer: Optimize state updates
typescript
// Performance Optimization in React Native
import React, { useMemo, useCallback, memo } from 'react';

// Memoized component
const MemoizedItem = memo(({ item, onPress }) => {
  console.log('Rendering item:', item.id);
  return (
    <TouchableOpacity
      style={styles.item}
      onPress={() => onPress(item.id)}
    >
      <Text style={styles.itemText}>{item.name}</Text>
    </TouchableOpacity>
  );
});

const App = () => {
  const [items, setItems] = useState([]);
  const [filter, setFilter] = useState('');
  const [count, setCount] = useState(0);
  
  // Memoize expensive computation
  const expensiveCalculation = useMemo(() => {
    console.log('Calculating total...');
    return items.reduce((sum, item) => sum + item.value, 0);
  }, [items]);
  
  // Memoize filtered items
  const filteredItems = useMemo(() => {
    console.log('Filtering items...');
    if (!filter) return items;
    return items.filter(item => 
      item.name.toLowerCase().includes(filter.toLowerCase())
    );
  }, [items, filter]);
  
  // Memoize callback functions
  const handleItemPress = useCallback((id) => {
    console.log('Item pressed:', id);
    setItems(prev => prev.map(item => 
      item.id === id ? { ...item, selected: true } : item
    ));
  }, []);
  
  const handleAddItem = useCallback(() => {
    setItems(prev => [
      ...prev,
      { id: Date.now(), name: `Item ${prev.length + 1}`, value: Math.floor(Math.random() * 100) }
    ]);
  }, []);
  
  // Optimize list rendering
  const renderItem = useCallback(({ item }) => (
    <MemoizedItem item={item} onPress={handleItemPress} />
  ), [handleItemPress]);
  
  return (
    <View style={styles.container}>
      <Text style={styles.title}>Performance Demo</Text>
      <Text>Total: {expensiveCalculation}</Text>
      <Text>Count: {count}</Text>
      
      <TextInput
        style={styles.input}
        placeholder="Filter items..."
        value={filter}
        onChangeText={setFilter}
      />
      
      <Button title="Add Item" onPress={handleAddItem} />
      <Button title="Increment" onPress={() => setCount(c => c + 1)} />
      
      <FlatList
        data={filteredItems}
        renderItem={renderItem}
        keyExtractor={item => item.id.toString()}
        removeClippedSubviews={true}
        maxToRenderPerBatch={10}
        updateCellsBatchingPeriod={50}
        windowSize={10}
        initialNumToRender={10}
        getItemLayout={(data, index) => ({
          length: 60,
          offset: 60 * index,
          index,
        })}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20 },
  title: { fontSize: 24, fontWeight: 'bold', marginBottom: 20 },
  input: { borderWidth: 1, borderColor: '#ccc', padding: 10, marginVertical: 10 },
  item: { padding: 10, borderWidth: 1, borderColor: '#eee', marginVertical: 2 },
  itemText: { fontSize: 16 }
});