Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 71 ยท Projects

Project: Chat App UI

Build a chat screen in React Native: an inverted FlatList, keyboard handling, optimistic sending with message status and retry, using a runnable fake socket.

A chat screen looks easy until you try to build one. New messages appear at the bottom, the list must stay glued to the newest message, the keyboard pushes everything up, your own message must show instantly even though the server has not answered yet, and when the connection drops, the user needs to see which message failed and be able to retry it.

This project builds the interface and the client-side logic for exactly those problems. The server is replaced by a fake socket so everything is deterministic. You will use an inverted list, optimistic updates with a per-message status, and keyboard avoidance. It builds on FlatList Essentials, ScrollView and Keyboard Handling and Networking with fetch.

What runs on this site. FlatList, KeyboardAvoidingView and real WebSockets need a native runtime or a server, so the real screen is read-only. The runnable examples are stand-ins: a fake socket built from timers (it answers, fails or replies on a schedule you can predict), and an HTML view that reverses the list with CSS the way an inverted FlatList does. Message texts and replies are invented sample content.

What makes chat different

Four chat problems

Stick to bottom Newest message stays visible.
Keyboard The composer rides above it.
Instant feel Show my message right away.
Failure Mark it and offer retry.
1 / 2

The inverted list

A normal list starts at the top and the newest item is at the bottom, which is off screen as soon as there are enough messages. Chat apps flip the model: the data is stored newest first, and the list is inverted, so index 0 is drawn at the bottom and older messages stack upward. The user's scroll position at "no scrolling" is the newest message, new messages appear without any scroll code, and loading older history is just onEndReached.

In React Native you pass one prop:

JSX
<FlatList
  data={messages}            // newest first
  inverted
  keyExtractor={(m) => m.id}
  renderItem={({ item }) => <Bubble message={item} />}
  keyboardShouldPersistTaps="handled"
  onEndReached={loadOlder}   // "end" is the top of the screen in an inverted list
  onEndReachedThreshold={0.5}
/>

inverted flips the list with a transform (a vertical scale of -1 on the list and each row), so styles that depend on direction, such as padding at the top, appear swapped. Read the props carefully: ListHeaderComponent renders at the bottom of an inverted list, and ListFooterComponent at the top. That is the right place for a typing indicator ("Alex is typing...") and a "loading older messages" spinner respectively.

Message model and status

Each message is { id, text, from, status, createdAt }. The id is generated by the client (a UUID) so we can refer to the message before the server has seen it. This is what makes an optimistic update possible: when the server acknowledges id: "c1", we know which bubble to update.

The status moves along a short path:

  • sending while the request is in flight,
  • sent when the server acknowledges,
  • delivered when the recipient's device got it (optional in real apps),
  • failed when something went wrong, which allows retry.

Incoming messages from others have no status, they simply arrive.

The reducer

JavaScript
export function chatReducer(messages, action) {
  switch (action.type) {
    case 'send':
      return [{ id: action.id, text: action.text, from: 'me', status: 'sending' }, ...messages];
    case 'status':
      return messages.map((m) => (m.id === action.id ? { ...m, status: action.status } : m));
    case 'receive':
      return [{ id: action.id, text: action.text, from: 'them' }, ...messages];
    default:
      return messages;
  }
}

Putting a new message at the front of the array is what lines up with inverted. The reducer never talks to the network. A separate hook connects the socket and dispatches events, which keeps the pure part easy to test.

The socket hook

Real apps use a WebSocket or a library on top of it. The hook's job is to translate between socket events and reducer actions, and to expose a send and retry function to the screen.

JavaScript
import { useEffect, useReducer, useRef } from 'react';

export function useChat(socket) {
  const [messages, dispatch] = useReducer(chatReducer, []);
  const counter = useRef(0);

  useEffect(() => {
    return socket.subscribe((event) => {
      if (event.type === 'ack') dispatch({ type: 'status', id: event.id, status: 'sent' });
      if (event.type === 'delivered') dispatch({ type: 'status', id: event.id, status: 'delivered' });
      if (event.type === 'error') dispatch({ type: 'status', id: event.id, status: 'failed' });
      if (event.type === 'message') dispatch({ type: 'receive', id: event.id, text: event.text });
    });
  }, [socket]);

  function send(text) {
    const trimmed = text.trim();
    if (!trimmed) return;
    const id = 'c' + ++counter.current;
    dispatch({ type: 'send', id, text: trimmed });
    socket.send({ id, text: trimmed });
  }

  function retry(message) {
    dispatch({ type: 'status', id: message.id, status: 'sending' });
    socket.send({ id: message.id, text: message.text });
  }

  return { messages, send, retry };
}

Returning the unsubscribe function from the effect is important: if the screen unmounts and the listener stays, it would later dispatch into a component that no longer exists. In real code the id would be a UUID (the counter would restart on every app launch and produce duplicates in a stored history).

A fake socket you can predict

To develop the UI without a server we build an object with the same shape: subscribe(listener) and send(message). It acknowledges after a delay, fails when the text contains the word fail, and replies with an echo so you see incoming messages. Using a small latency makes the demo quick.

Fake socket and message status machine

Read the log from top to bottom. Both messages appear as sending instantly (the optimistic part). Then the first moves to sent, then delivered, and a reply arrives. The second ends as failed. The UI never has to ask "did it work?": it only displays whatever status each message currently has.

Keyboard handling and the composer

The composer (text field plus Send button) sits below the list. When the keyboard opens it must move up with it. On iOS, KeyboardAvoidingView with behavior="padding" does this; on Android with the default adjustResize window mode the system resizes the window and you usually need nothing extra (check the softwareKeyboardLayoutMode in your app config, covered in Project Structure and App Config).

JSX
import { KeyboardAvoidingView, Platform, Pressable, StyleSheet, Text, TextInput, View } from 'react-native';

function ChatScreen({ socket }) {
  const { messages, send, retry } = useChat(socket);
  const [draft, setDraft] = useState('');

  function submit() {
    send(draft);
    setDraft('');
  }

  return (
    <KeyboardAvoidingView
      style={{ flex: 1 }}
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
      keyboardVerticalOffset={Platform.OS === 'ios' ? 90 : 0}
    >
      <FlatList
        data={messages}
        inverted
        keyExtractor={(m) => m.id}
        keyboardShouldPersistTaps="handled"
        renderItem={({ item }) => <Bubble message={item} onRetry={() => retry(item)} />}
      />
      <View style={styles.composer}>
        <TextInput
          style={styles.input}
          value={draft}
          onChangeText={setDraft}
          placeholder="Message"
          multiline
          maxLength={2000}
        />
        <Pressable style={styles.send} onPress={submit} disabled={!draft.trim()}>
          <Text style={styles.sendLabel}>Send</Text>
        </Pressable>
      </View>
    </KeyboardAvoidingView>
  );
}

keyboardVerticalOffset accounts for the navigation header, which sits above the avoiding view; tune it on a real device. Notice keyboardShouldPersistTaps="handled": without it, tapping a failed message to retry would first just close the keyboard.

Each Bubble aligns right for from: 'me' and left otherwise, shows the status as a small caption, and turns a failed message into a tappable "Not sent. Tap to retry" line. Always provide a text label as well as color, so the state is clear to every user and to screen readers (see Accessibility in React Native).

Chat screen with optimistic send, retry and an inverted view (stand-in)

Send "hello" and watch the label change from Sending to Sent to Delivered before the echo arrives. Send "this will fail": the bubble appears immediately, then flips to the red retry line. Press it, and the fake socket (which only fails the first attempt) lets the retry through. In a real app, retries use the same message id, so the server can recognise a duplicate if the first attempt actually succeeded and only the acknowledgement was lost.

What a production chat adds

  • Reconnection with exponential backoff, and a queue of unsent messages that are retried in order.
  • Pagination of history with onEndReached, and care about duplicates when a live message arrives during a page load.
  • Message grouping (consecutive messages from one sender share a bubble shape) and date separators, which are just extra items in the data array.
  • Read receipts, typing indicators and presence, each a small socket event with its own reducer case.
  • Memoized rows: wrap Bubble in React.memo and keep renderItem stable (Fast Lists: Virtualization and Tuning), because an active chat re-renders constantly.
  • Push notifications when the app is in the background (Push Notifications).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a chat built with an inverted FlatList, in which order should the data array be?

    An inverted list draws index 0 at the bottom, so storing newest first puts the latest message at the bottom and lets older ones stack upward.
  2. 2. What is an optimistic update in a chat?

    The UI assumes success and shows the message right away. The status then changes to sent or failed when the real result is known.
  3. 3. Why does the client generate the message id?

    The bubble exists before the server has seen it. A client id lets acks and errors find it, and a retry can reuse the same id to avoid duplicates.
  4. 4. In an inverted list, where does ListHeaderComponent appear?

    Inversion flips the list, so the header is drawn at the bottom and the footer at the top. The header is a good place for a typing indicator.
  5. 5. Why return the unsubscribe function from the useEffect that subscribes to the socket?

    Without cleanup, old listeners keep dispatching after the screen is gone, causing leaks and duplicate updates.

Summary

  • Store messages newest first and use inverted so the latest message sits at the bottom without any scroll code.
  • Give every message a client-generated id and its own status (sending, sent, delivered, failed); show sends optimistically and offer retry with the same id.
  • Keep the reducer pure and translate socket events into actions in a hook that cleans up its subscription.
  • Use KeyboardAvoidingView (iOS padding), keyboardShouldPersistTaps="handled" and a text label for every state.
  • On this site the native list and socket are read-only; the fake socket and the status machine run for real.

Next, store data in a database and draw charts in Project: Habit and Fitness Tracker.