Short-Video App with React Native and Supabase · Course book
Chapter 13: Likes
The like button is the simplest interaction in a social app and one of the most revealing tests of good engineering. It must respond instantly to a tap, show the right state on every video the user scrolls past, never let one person like the same video twice, keep counts correct, and do all of this without sending a flood of requests. This chapter builds likes and unlikes for the short-video app: the Like table and its constraints, toggling a like, knowing which videos the user has liked without asking the server for each one, optimistic updates that make the button feel instant, and counting the likes on a video and across a user's profile, with the request savings worked out by hand.
The Like table and its rules
A like is a row connecting a user and a video. The Like table stores the id of the user who liked, the id of the video, the id of the video's owner and the time. Storing the owner's id lets the profile screen count "likes received" and the activity feed list "who liked my videos" with a simple filter on one table.
Two rules belong in the database, where no bug in the app can break them. A unique constraint on the pair of user and video means a second like from the same user is rejected outright. And row level security policies allow a signed-in user to insert a like only when its user id is their own, and to delete only their own likes. Reading likes can be open to all signed-in users, since like counts are public information in a social app.
| Action | Database operation | Rule that protects it |
|---|---|---|
| Like a video | Insert a row with user, video and owner ids | Unique on (user_id, video_id); insert only as yourself |
| Unlike a video | Delete the row for this user and video | Delete only your own rows |
| Show a video's likes | Count rows for the video | Readable by signed-in users |
| Show likes received | Count rows for the owner | Readable by signed-in users |
| Know what I liked | Select video ids for the current user | Readable by signed-in users |
Toggling a like
The heart icon is a toggle: if the user has not liked the video, tapping it inserts a like; if they have, tapping removes it. The app decides which by checking its record of the user's likes.
async function toggleLike(video) {
const liked = likedIds.has(video.id);
if (liked) {
await supabase.from("Like").delete()
.eq("user_id", user.id).eq("video_id", video.id);
} else {
await supabase.from("Like").insert({
user_id: user.id, video_id: video.id, video_user_id: video.user_id,
});
}
}
Because the unique constraint exists, even a double tap that sends two inserts cannot create two likes: the second insert fails, and the app can safely ignore that particular error. Disabling the button for the moment a request is in flight is still sensible, so the icon does not flicker between states. Users should also be able to like their own videos or not, according to the app's design; whichever you choose, apply it consistently in both the interface and the policies.
Knowing what the user has liked
Every video in the feed must show a filled or empty heart, so the app must know, for each video, whether the current user has liked it. The obvious approach, asking the database "has this user liked this video?" for each video as it appears, sends one request per video, which adds up quickly as people scroll.
A better approach loads the user's likes once, when the app starts or the user signs in: a single query selects the ids of all the videos the user has liked and stores them in a JavaScript Set, kept in the auth provider or a small store. Checking a video is then likedIds.has(video.id), a local lookup that takes no time and no network. When the user likes or unlikes, the app updates the set at the same time as the database.
Where the set lives matters. If each feed item kept its own copy of "liked or not", a video liked in the feed might still show an empty heart when the same video appears on the creator's profile a moment later. Keeping one shared source of truth, the set in a provider or store, and having every heart read from it, guarantees that all screens agree. React re-renders only the components that read the changed value, as long as the set is replaced with a new one on each change rather than modified in place, because React detects changes by comparing references. A common pattern is to create a new set containing the old ids plus or minus the one that changed, and store that.
The set should also be cleared when the user signs out and reloaded when someone else signs in on the same phone; otherwise the next user would briefly see the previous user's likes, a small but embarrassing privacy leak.
Optimistic updates
A like that waits for the server before the heart fills feels sluggish, especially on a slow connection where a round trip can take half a second or more. An optimistic update changes the interface first and confirms with the server afterwards. When the user taps, the app immediately fills the heart, adds the id to the liked set and increases the visible count by one; then it sends the insert. If the request succeeds, nothing more is needed. If it fails, the app rolls back: it empties the heart, removes the id and decreases the count, and perhaps shows a brief message.
TanStack Query supports this pattern directly in its mutations: an onMutate function updates the cached data and returns a snapshot of the previous state, an onError function restores the snapshot, and an onSettled function refetches to make sure the cache matches the server. The result is a button that feels instant on any network while staying correct.
Optimism suits likes particularly well because they almost always succeed and a rare failure is harmless. The same technique would be risky for actions where failure matters more, such as a payment, which should wait for confirmation before telling the user it worked.
Counting likes on videos and profiles
Each video shows how many likes it has, and each profile shows the total likes received across all of the user's videos. Both are counts of rows in the Like table: filtered by video_id for a video, and by video_user_id for a profile. Supabase can return a count without downloading the rows themselves, by asking for an exact count with a head-only request, which is quick when the filtered column has an index.
For a feed, counting separately for every video brings back the one-request-per-video problem. Two better approaches exist. The feed query can include each video's like count through a related-rows count in the same select, so one request returns videos and counts together. Or the Video table can store a running like_count, kept up to date by a database trigger that adds one when a like is inserted and subtracts one when it is deleted; reads are then free, at the cost of a little extra work on each write.
Whichever method is used, the number shown is a snapshot. Other people may like the video while you watch, so counts can be refreshed when the video becomes active, or updated live with real-time subscriptions for the most popular videos, a technique covered in the chapter on chat. For most apps, refreshing on scroll is accurate enough, and users rarely notice a count that is a few seconds old, as long as their own like is reflected at once.
Practice tasks
- A user views 45 videos and has liked 1,200 videos in total. How many requests does each approach in Figure 13.1 need, if pages hold 15 videos?
- Estimate the memory used by a set of 10,000 UUIDs of 36 characters each.
- Describe the steps of an optimistic like, including the rollback if the insert fails.
- Write the two filters used to count a video's likes and a user's likes received.
- Explain why the unique constraint makes a double tap harmless.
- Compare counting likes in the feed query with storing a running count updated by a trigger.
This course book is available to read online only at tech-academy.chrysolites.org.