📖 Scenario: You are building a simple chat app using Supabase for realtime updates. You want to show new messages as they arrive without refreshing the page.
🎯 Goal: Create a React component that connects to Supabase realtime messages using React hooks. The component should display a list of messages and update automatically when new messages arrive.
📋 What You'll Learn
Create a state variable called messages to hold the list of chat messages.
Create a Supabase client instance called supabase with the given URL and anon key.
Use useEffect to subscribe to the messages table realtime updates.
Update the messages state when a new message is inserted.
Render the list of messages inside a <ul> element.
💡 Why This Matters
🌍 Real World
Realtime chat apps, live dashboards, notifications, and collaborative tools use realtime data updates to improve user experience.
💼 Career
Understanding how to integrate realtime data streams with React hooks and cloud services like Supabase is valuable for frontend and full-stack developers building interactive web apps.
Progress0 / 4 steps
1
Setup initial messages state
Create a React state variable called messages initialized to an empty array using useState.
Supabase
Hint
Use const [messages, setMessages] = useState([]); inside the Chat function.
2
Create Supabase client
Create a Supabase client instance called supabase using createClient(supabaseUrl, supabaseAnonKey).
Supabase
Hint
Use const supabase = createClient(supabaseUrl, supabaseAnonKey); inside the Chat function.
3
Subscribe to realtime messages
Use useEffect to subscribe to the messages table realtime inserts with supabase.channel('public:messages').on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'messages' }, callback).subscribe(). In the callback, update messages state by appending the new message using setMessages(prev => [...prev, payload.new]). Clean up the subscription on unmount.
Supabase
Hint
Use useEffect with an empty dependency array except supabase. Subscribe to realtime inserts on messages table and update state inside the callback. Clean up subscription on unmount.
4
Render messages list
Render the messages array inside a <ul> element. For each message, render a <li> with key set to message.id and display message.content.
Supabase
Hint
Use return ( <ul> {messages.map(message => <li key={message.id}>{message.content}</li>)} </ul> ) to render the messages.
Practice
(1/5)
1. What is the main purpose of using Realtime with React hooks in a Supabase app?
easy
A. To handle user authentication manually
B. To style the app components dynamically
C. To update the app instantly when data changes in the database
D. To fetch data only once when the app loads
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 C
Quick Check:
Realtime updates = instant app data refresh [OK]
Hint: Realtime means instant updates on data change [OK]
Common Mistakes:
Confusing realtime with styling or authentication
Thinking it fetches data only once
Assuming it handles user login
2. Which React hook is commonly used to subscribe and clean up Supabase realtime events?
easy
A. useEffect
B. useState
C. useMemo
D. useContext
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 A
Quick Check:
Subscriptions need useEffect [OK]
Hint: useEffect manages setup and cleanup of subscriptions [OK]
Common Mistakes:
Using useState for subscriptions
Confusing useMemo with side effects
Thinking useContext handles subscriptions
3. Given this React code snippet using Supabase realtime subscription:
But the app does not update when tasks change. What is the likely problem?
medium
A. The setTasks function is used incorrectly
B. The event type 'UPDATE' is invalid
C. useEffect should not have an empty dependency array
D. The subscription is missing the .subscribe() call
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 D
Quick Check:
Missing .subscribe() means no updates [OK]
Hint: Always call .subscribe() after .on() for realtime [OK]
Common Mistakes:
Forgetting .subscribe() after .on()
Thinking event type 'UPDATE' is wrong
Misusing setTasks function
Changing dependency array unnecessarily
5. You want to build a React component that listens to both INSERT and DELETE events on a Supabase 'comments' table and updates the state accordingly. Which approach correctly handles both events and cleans up subscriptions?
hard
A. Use one subscription with .on('INSERT') only, ignoring DELETE events
B. Use two separate subscriptions inside one useEffect, each with .subscribe(), and remove both on cleanup
C. Use useEffect without cleanup function to keep subscriptions alive
D. Subscribe to 'comments' table outside useEffect and update state directly
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 B