0
0
React Nativemobile~20 mins

React.memo and useMemo in React Native - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Memo Demo Screen
This screen shows a list of numbers and a button to add random numbers. It uses React.memo to avoid re-rendering list items unnecessarily and useMemo to memoize the sum calculation.
Target UI
-------------------------
| Memo Demo Screen       |
|-----------------------|
| Numbers:              |
| 1                     |
| 2                     |
| 3                     |
|                       |
| Sum: 6                |
|                       |
| [Add Random Number]    |
-------------------------
Display a list of numbers using a child component wrapped with React.memo
Add a button that adds a random number to the list
Calculate and display the sum of numbers using useMemo to avoid recalculating on unrelated renders
Ensure the list items do not re-render when the sum changes
Starter Code
React Native
import React, { useState, useMemo } from 'react';
import { View, Text, Button, FlatList, StyleSheet } from 'react-native';

const NumberItem = React.memo(({ value }) => {
  console.log('Rendering item:', value);
  return <Text style={styles.item}>{value}</Text>;
});

export default function MemoDemoScreen() {
  const [numbers, setNumbers] = useState([1, 2, 3]);

  // TODO: Calculate sum using useMemo

  // TODO: Add function to add random number

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Numbers:</Text>
      <FlatList
        data={numbers}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item }) => <NumberItem value={item} />}
      />
      <Text style={styles.sum}>Sum: {/* TODO: show sum here */}</Text>
      <Button title="Add Random Number" onPress={() => { /* TODO: add number */ }} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20 },
  title: { fontSize: 20, marginBottom: 10 },
  item: { fontSize: 18, paddingVertical: 4 },
  sum: { fontSize: 18, marginVertical: 20 }
});
Task 1
Task 2
Task 3
Task 4
Solution
React Native
import React, { useState, useMemo } from 'react';
import { View, Text, Button, FlatList, StyleSheet } from 'react-native';

const NumberItem = React.memo(({ value }) => {
  console.log('Rendering item:', value);
  return <Text style={styles.item}>{value}</Text>;
});

export default function MemoDemoScreen() {
  const [numbers, setNumbers] = useState([1, 2, 3]);

  const sum = useMemo(() => {
    console.log('Calculating sum');
    return numbers.reduce((acc, val) => acc + val, 0);
  }, [numbers]);

  const addRandomNumber = () => {
    const randomNum = Math.floor(Math.random() * 100) + 1;
    setNumbers(prev => [...prev, randomNum]);
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Numbers:</Text>
      <FlatList
        data={numbers}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item }) => <NumberItem value={item} />}
      />
      <Text style={styles.sum}>Sum: {sum}</Text>
      <Button title="Add Random Number" onPress={addRandomNumber} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20 },
  title: { fontSize: 20, marginBottom: 10 },
  item: { fontSize: 18, paddingVertical: 4 },
  sum: { fontSize: 18, marginVertical: 20 }
});

We wrapped the NumberItem component with React.memo so it only re-renders when its value prop changes. This avoids unnecessary re-renders when the sum changes.

The sum is calculated using useMemo which caches the result and only recalculates when the numbers array changes. This improves performance by skipping sum calculation on unrelated renders.

The addRandomNumber function adds a new random number to the list, triggering a re-render and recalculation of the sum.

This example shows how React.memo and useMemo help optimize React Native apps by reducing unnecessary work.

Final Result
Completed Screen
-------------------------
| Memo Demo Screen       |
|-----------------------|
| Numbers:              |
| 1                     |
| 2                     |
| 3                     |
| 57                    |
|                       |
| Sum: 63               |
|                       |
| [Add Random Number]    |
-------------------------
Tapping 'Add Random Number' adds a new random number to the list below the existing numbers.
The sum updates to show the new total of all numbers.
Only the new number item re-renders; existing items do not re-render.
Sum recalculation happens only when numbers change, not on other state changes.
Stretch Goal
Add a toggle button to switch between light and dark mode for the screen.
💡 Hint
Use React state to track mode and apply conditional styles for background and text colors.