Bird
Raised Fist0
Supabasecloud~20 mins

Realtime with React hooks in Supabase - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Supabase Realtime Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ service_behavior
intermediate
2:00remaining
Understanding Supabase Realtime Subscription Behavior

Given a React component using Supabase's realtime subscription with hooks, what will be the output in the console when a new row is inserted into the subscribed table?

Supabase
import { useEffect } from 'react';
import { createClient } from '@supabase/supabase-js';

const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key');

function RealtimeComponent() {
  useEffect(() => {
    const subscription = supabase
      .from('messages')
      .on('INSERT', payload => {
        console.log('New message:', payload.new);
      })
      .subscribe();

    return () => {
      subscription.unsubscribe();
    };
  }, []);

  return null;
}
AThe console logs the new row object inserted into 'messages' table.
BThe console logs the entire table 'messages' contents.
CThe console logs nothing because the subscription is not active.
DThe console logs an error because 'removeSubscription' is deprecated.
Attempts:
2 left
💡 Hint

Think about what the 'on' method with 'INSERT' event listens for and what 'payload.new' contains.

❓ Configuration
intermediate
2:00remaining
Correct Cleanup of Supabase Realtime Subscription in React

Which option correctly cleans up the Supabase realtime subscription inside a React useEffect hook to avoid memory leaks?

Supabase
useEffect(() => {
  const subscription = supabase
    .from('notifications')
    .on('UPDATE', payload => {
      console.log('Updated:', payload.new);
    })
    .subscribe();

  // Cleanup function here
  return () => {
    // ???
  };
}, []);
Areturn () => { supabase.removeSubscription(subscription); };
Breturn () => { supabase.from('notifications').unsubscribe(); };
Creturn () => { supabase.channel('notifications').unsubscribe(); };
Dreturn () => { subscription.unsubscribe(); };
Attempts:
2 left
💡 Hint

Check the Supabase client API for unsubscribing from realtime subscriptions.

❓ Architecture
advanced
2:00remaining
Designing a Scalable Realtime Notification System with Supabase and React

You want to build a realtime notification system using Supabase and React hooks. Which architectural choice best ensures minimal resource usage on the client while keeping notifications up-to-date?

ASubscribe to all database changes on the notifications table and filter updates client-side.
BSubscribe only to notifications relevant to the logged-in user using filtered channels.
CPoll the notifications table every 5 seconds using a React interval hook.
DFetch all notifications once on component mount and never update again.
Attempts:
2 left
💡 Hint

Consider how to reduce unnecessary data sent to the client and avoid excessive network usage.

❓ security
advanced
2:00remaining
Securing Realtime Subscriptions in Supabase with Row-Level Security

How can you ensure that a user only receives realtime updates for rows they are authorized to see in Supabase?

AEnable Row-Level Security (RLS) policies on the table and use Supabase's authenticated realtime channels.
BFilter data client-side after receiving all realtime updates.
CDisable RLS and rely on client-side checks to hide unauthorized data.
DUse a global subscription to all table changes and ignore unauthorized rows.
Attempts:
2 left
💡 Hint

Think about how Supabase enforces data access control on the server side.

✅ Best Practice
expert
2:00remaining
Optimizing React Components for Supabase Realtime Data Updates

Which approach best prevents unnecessary re-renders in a React component subscribed to Supabase realtime updates?

ARecreate the subscription on every render to get fresh data.
BUse useState to store all realtime data and update state on every event without memoization.
CUse useRef to store the latest data and only update state when data changes meaningfully, combined with React.memo.
DUpdate state directly inside the subscription callback without any checks.
Attempts:
2 left
💡 Hint

Consider how React re-renders components when state changes and how to minimize updates.

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

  1. 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.
  2. 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.
  3. Final Answer:

    To update the app instantly when data changes in the database -> Option C
  4. 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

  1. 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.
  2. Step 2: Match with Supabase realtime subscription

    Supabase realtime subscriptions need to be set up and cleaned up properly, which useEffect handles well.
  3. Final Answer:

    useEffect -> Option A
  4. 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:
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?
medium
A. The new message is added to the messages state array
B. The messages state is reset to an empty array
C. The subscription stops listening for new messages
D. An error occurs because setMessages is called incorrectly

Solution

  1. Step 1: Analyze the subscription callback

    On 'INSERT' event, the callback adds the new message (payload.new) to the current messages array using setMessages.
  2. Step 2: Understand state update behavior

    setMessages uses a function to append the new message, preserving existing messages and adding the new one.
  3. Final Answer:

    The new message is added to the messages state array -> Option A
  4. Quick Check:

    INSERT event appends new message [OK]
Hint: INSERT event adds new data to state array [OK]
Common Mistakes:
  • Thinking state resets instead of appending
  • Assuming subscription stops on insert
  • Believing setMessages usage is incorrect here
4. You wrote this React useEffect to subscribe to Supabase realtime updates:
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?
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

  1. Step 1: Check subscription setup

    The code calls .on() but does not call .subscribe(), so the subscription is never activated.
  2. Step 2: Confirm event type and state update

    'UPDATE' is valid and setTasks usage is correct; empty dependency array is appropriate here.
  3. Final Answer:

    The subscription is missing the .subscribe() call -> Option D
  4. 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

  1. Step 1: Understand multiple event subscriptions

    To listen to both INSERT and DELETE, create two subscriptions with .on('INSERT') and .on('DELETE').
  2. Step 2: Manage subscriptions lifecycle

    Inside useEffect, subscribe to both and return a cleanup function that removes both subscriptions to avoid memory leaks.
  3. Final Answer:

    Use two separate subscriptions inside one useEffect, each with .subscribe(), and remove both on cleanup -> Option B
  4. Quick Check:

    Multiple subscriptions + cleanup = correct approach [OK]
Hint: Subscribe separately for each event and clean up both [OK]
Common Mistakes:
  • Ignoring DELETE events
  • Not cleaning up subscriptions
  • Subscribing outside useEffect causing leaks
  • Using only one event subscription
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard