Realtime with React hooks in Supabase - Time & Space Complexity
When using Supabase realtime with React hooks, we want to know how the number of updates affects the work done.
We ask: How does the app's work grow as more realtime events come in?
Analyze the time complexity of subscribing to realtime updates and handling them in React.
const [messages, setMessages] = useState([]);
useEffect(() => {
const subscription = supabase
.channel('public:messages')
.on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'messages' }, payload => {
setMessages(current => [...current, payload.new]);
})
.subscribe();
return () => {
supabase.removeChannel(subscription);
};
}, []);
This code listens for new messages and adds them to the list in React state.
Look at what repeats as more messages arrive.
- Primary operation: Receiving and processing each new message event from Supabase.
- How many times: Once per new message inserted in the database.
Each new message triggers one update to the React state array.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 | 10 updates to state, 10 event callbacks |
| 100 | 100 updates to state, 100 event callbacks |
| 1000 | 1000 updates to state, 1000 event callbacks |
Pattern observation: The work grows directly with the number of new messages received.
Time Complexity: O(n)
This means the work grows in a straight line as more realtime events come in.
[X] Wrong: "The subscription only runs once, so the work is constant no matter how many messages arrive."
[OK] Correct: Each new message triggers a callback and state update, so work grows with the number of messages.
Understanding how realtime updates affect app work helps you design responsive and efficient interfaces.
What if we batch multiple messages before updating state? How would the time complexity change?
Practice
Solution
Step 1: Understand Realtime with React hooks
Realtime with React hooks allows the app to listen for changes in the database and update the UI immediately.Step 2: Identify the main purpose
The main goal is to keep the app data fresh without manual refresh by updating instantly on data changes.Final Answer:
To update the app instantly when data changes in the database -> Option CQuick Check:
Realtime updates = instant app data refresh [OK]
- Confusing realtime with styling or authentication
- Thinking it fetches data only once
- Assuming it handles user login
Solution
Step 1: Recall React hooks for side effects
useEffect is designed to run code on component mount and clean up on unmount, perfect for subscriptions.Step 2: Match with Supabase realtime subscription
Supabase realtime subscriptions need to be set up and cleaned up properly, which useEffect handles well.Final Answer:
useEffect -> Option AQuick Check:
Subscriptions need useEffect [OK]
- Using useState for subscriptions
- Confusing useMemo with side effects
- Thinking useContext handles subscriptions
const [messages, setMessages] = useState([]);
useEffect(() => {
const subscription = supabase
.from('messages')
.on('INSERT', payload => {
setMessages(current => [...current, payload.new]);
})
.subscribe();
return () => {
supabase.removeSubscription(subscription);
};
}, []);What happens when a new message is inserted into the 'messages' table?
Solution
Step 1: Analyze the subscription callback
On 'INSERT' event, the callback adds the new message (payload.new) to the current messages array using setMessages.Step 2: Understand state update behavior
setMessages uses a function to append the new message, preserving existing messages and adding the new one.Final Answer:
The new message is added to the messages state array -> Option AQuick Check:
INSERT event appends new message [OK]
- Thinking state resets instead of appending
- Assuming subscription stops on insert
- Believing setMessages usage is incorrect here
useEffect(() => {
supabase
.from('tasks')
.on('UPDATE', payload => {
setTasks(tasks.map(t => t.id === payload.new.id ? payload.new : t));
});
}, []);But the app does not update when tasks change. What is the likely problem?
Solution
Step 1: Check subscription setup
The code calls .on() but does not call .subscribe(), so the subscription is never activated.Step 2: Confirm event type and state update
'UPDATE' is valid and setTasks usage is correct; empty dependency array is appropriate here.Final Answer:
The subscription is missing the .subscribe() call -> Option DQuick Check:
Missing .subscribe() means no updates [OK]
- Forgetting .subscribe() after .on()
- Thinking event type 'UPDATE' is wrong
- Misusing setTasks function
- Changing dependency array unnecessarily
Solution
Step 1: Understand multiple event subscriptions
To listen to both INSERT and DELETE, create two subscriptions with .on('INSERT') and .on('DELETE').Step 2: Manage subscriptions lifecycle
Inside useEffect, subscribe to both and return a cleanup function that removes both subscriptions to avoid memory leaks.Final Answer:
Use two separate subscriptions inside one useEffect, each with .subscribe(), and remove both on cleanup -> Option BQuick Check:
Multiple subscriptions + cleanup = correct approach [OK]
- Ignoring DELETE events
- Not cleaning up subscriptions
- Subscribing outside useEffect causing leaks
- Using only one event subscription
Ready to prove it?
Pass the test and this pattern moves unknown
