Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 71 ยท Projects

Project: Todo App

Build a React Native todo app: a reducer for the logic, FlatList for the view, a TextInput to add items and AsyncStorage to persist them, with runnable stand-ins.

A todo app is small enough to finish in an afternoon, yet it touches almost every idea a real mobile app needs: state, a list, a text field, touch feedback and saving data between launches. In this project you build all of it, in the order a professional would: logic first, view second, storage last.

The plan is deliberately boring in a good way. We keep the rules of the app (add, toggle, remove, clear) in one pure function called a reducer. The screen only displays the state and sends actions. Storage is a thin adapter around that state. If you know State in React Native Apps and FlatList Essentials, this is where they come together.

What runs on this site. React Native itself needs a phone or an emulator, so the real code in this lesson is read-only. The runnable examples are stand-ins: the reducer is exactly the code you would ship (it is plain JavaScript), the screen is drawn with HTML instead of native views, and the storage is an in-memory object with the same getItem / setItem shape as AsyncStorage.

What we are building

The finished app has four features:

  • A text field and an Add button at the top.
  • A list of todos. Tapping a row toggles it done; a small button removes it.
  • A footer that says how many items are left, with filter buttons (All, Active, Done).
  • Persistence: close the app, open it again, and your todos are still there.

Build it in three layers

Logic A pure reducer decides every change.
View FlatList, TextInput and Pressable.
Storage Load once, save on change.

Each layer can be tested without the others.

1 / 2

Step 1: the logic as a reducer

A todo is a tiny object: { id, text, done }. The whole list is an array of them. Every change the user can make becomes an action, and the reducer turns the old array plus an action into a new array. It never mutates the old one, which is what lets React notice that something changed.

JavaScript
export function todoReducer(state, action) {
  switch (action.type) {
    case 'load':
      return action.todos;
    case 'add': {
      const text = action.text.trim();
      if (!text) return state;
      return [...state, { id: action.id, text, done: false }];
    }
    case 'toggle':
      return state.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t));
    case 'remove':
      return state.filter((t) => t.id !== action.id);
    case 'clearDone':
      return state.filter((t) => !t.done);
    default:
      return state;
  }
}

Two details matter. First, the reducer ignores blank input: a user can tap Add with nothing typed, and the app should shrug. Second, the id comes from the caller, not from inside the reducer, because a reducer must be predictable. Calling Math.random() or Date.now() inside it would give different results for the same inputs. In the screen we create ids with a counter or crypto.randomUUID().

The todo reducer, step by step

Notice step two: the blank text returns the same array, so React skips the re-render. That is a free optimization you get by returning state untouched when nothing changes.

Step 2: the screen

Here is the real React Native screen, read-only on this site. useReducer holds the list, a separate useState holds the text being typed, and a FlatList draws the rows.

JSX
import { useReducer, useState } from 'react';
import { FlatList, Pressable, StyleSheet, Text, TextInput, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { todoReducer } from './todoReducer';

let nextId = 1;

export default function TodoScreen() {
  const [todos, dispatch] = useReducer(todoReducer, []);
  const [draft, setDraft] = useState('');

  function submit() {
    dispatch({ type: 'add', id: String(nextId++), text: draft });
    setDraft('');
  }

  return (
    <SafeAreaView style={styles.screen}>
      <View style={styles.row}>
        <TextInput
          style={styles.input}
          value={draft}
          onChangeText={setDraft}
          onSubmitEditing={submit}
          placeholder="What needs doing?"
          returnKeyType="done"
        />
        <Pressable style={styles.add} onPress={submit} accessibilityRole="button">
          <Text style={styles.addLabel}>Add</Text>
        </Pressable>
      </View>

      <FlatList
        data={todos}
        keyExtractor={(t) => t.id}
        keyboardShouldPersistTaps="handled"
        ListEmptyComponent={<Text style={styles.empty}>Nothing to do. Enjoy!</Text>}
        renderItem={({ item }) => (
          <View style={styles.item}>
            <Pressable
              style={{ flex: 1 }}
              onPress={() => dispatch({ type: 'toggle', id: item.id })}
              accessibilityRole="checkbox"
              accessibilityState={{ checked: item.done }}
            >
              <Text style={[styles.text, item.done && styles.done]}>{item.text}</Text>
            </Pressable>
            <Pressable hitSlop={12} onPress={() => dispatch({ type: 'remove', id: item.id })}>
              <Text accessibilityLabel={'Delete ' + item.text}>โœ•</Text>
            </Pressable>
          </View>
        )}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  screen: { flex: 1, padding: 16 },
  row: { flexDirection: 'row', gap: 8, marginBottom: 12 },
  input: { flex: 1, borderWidth: 1, borderColor: '#cbd5e1', borderRadius: 8, paddingHorizontal: 12, height: 44 },
  add: { backgroundColor: '#2563eb', borderRadius: 8, paddingHorizontal: 16, justifyContent: 'center' },
  addLabel: { color: '#fff', fontWeight: '600' },
  item: { flexDirection: 'row', alignItems: 'center', paddingVertical: 12, minHeight: 48 },
  text: { fontSize: 16 },
  done: { textDecorationLine: 'line-through', color: '#94a3b8' },
  empty: { textAlign: 'center', color: '#64748b', marginTop: 32 },
});

A few choices deserve a comment. onSubmitEditing lets the keyboard's return key add the item, so the user never has to reach for the button. keyboardShouldPersistTaps="handled" means a tap on a row works even while the keyboard is open instead of just dismissing it. hitSlop enlarges the tiny delete symbol to a comfortable touch target, and the accessibility props tell a screen reader that each row is a checkbox and what its state is (see Accessibility in React Native).

Step 3: persistence

Without storage the list disappears every time the app restarts. The pattern is: load once when the screen mounts, then save whenever the list changes. The important trap is ordering. If you save on every change from the very first render, you overwrite the stored list with the empty initial array before the load finishes. A loaded flag prevents that.

JSX
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useEffect, useReducer, useState } from 'react';

const KEY = 'todos:v1';

function usePersistentTodos() {
  const [todos, dispatch] = useReducer(todoReducer, []);
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    AsyncStorage.getItem(KEY)
      .then((raw) => {
        dispatch({ type: 'load', todos: raw ? JSON.parse(raw) : [] });
      })
      .catch(() => {
        dispatch({ type: 'load', todos: [] });
      })
      .finally(() => setLoaded(true));
  }, []);

  useEffect(() => {
    if (loaded) {
      AsyncStorage.setItem(KEY, JSON.stringify(todos));
    }
  }, [todos, loaded]);

  return { todos, dispatch, loaded };
}

Two more habits are worth copying. The key has a version (v1), so a later release that changes the shape can migrate or discard old data cleanly. And the catch falls back to an empty list: corrupt JSON must never stop the app from opening. Storage options in depth are covered in Storing Data: AsyncStorage, MMKV and SecureStore.

Runnable todo app with a storage stand-in

Add two todos, tick one, then press Restart app. The screen remounts from scratch (like a cold start), shows "Loading saved todos...", and reads everything back from the storage stand-in. The stored JSON line below the app shows what a real AsyncStorage entry would contain. The "Stored JSON" line only refreshes when React re-renders the page, so it can lag one step behind the list.

Ideas to extend it

  • Edit a todo with a long press (onLongPress) that swaps the text for a TextInput.
  • Swipe to delete with a gesture library; see Reanimated and Gesture Handler.
  • Due dates and reminders with Push Notifications (local notifications need no server).
  • Move the reducer into a store such as Zustand when several screens share the list.
  • Test the reducer: it is a plain function, so a few Jest assertions cover the whole app logic.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the todo reducer return the same array for a blank text on add?

    Returning the previous state object tells React nothing changed, so it does not re-render. It is also the right behavior: an empty todo is not worth adding.
  2. 2. Why does the persistence hook keep a loaded flag?

    The save effect runs on the first render too. Without the flag it would write an empty array over the stored todos before the read completes.
  3. 3. What does keyboardShouldPersistTaps="handled" do on the FlatList?

    With the default setting, the first tap while the keyboard is up only dismisses the keyboard. handled lets children that handle the tap (like a Pressable) receive it.
  4. 4. Why is the id passed into the reducer instead of generated inside it?

    Generating ids with random values or timestamps inside the reducer would make it impure, which breaks testing and can cause different results between renders in development.

Summary

  • Build apps in layers: a pure reducer for the rules, a screen for display, an adapter for storage.
  • FlatList + Pressable + TextInput cover the view; use onSubmitEditing, hitSlop and accessibility props for a good mobile feel.
  • Persist by loading once and saving on change, guarded by a loaded flag, with a versioned key and a safe fallback for bad data.
  • On this site the native code is read-only; the reducer and storage logic run as real JavaScript in the stand-ins.

Next, add networking in Project: Weather App.