Supabase

How to Build Dark Mode with Supabase

Learn how to implement dark mode in your apps using Supabase with step-by-step instructions, code examples, and best practices for enhanced user experience.

Developer profile skeleton
Get a Free No-Code Consultation
Meet with Will, CEO at Bootstrapped to get a Free No-Code Consultation
Book a Call
Will Hawkins
CEO at Bootstrapped

How to Build Dark Mode with Supabase

 
Step 1: Set Up a Supabase Project
 

  • Go to the Supabase website and sign up/log in.
  • Create a new project by clicking on the "New Project" button.
  • Follow the prompts to set up your project and database. Remember to note down your Supabase URL and API Key as these will be required later.

 
Step 2: Set Up Your Frontend
 

  • Create a new frontend application if you don't have one. For example, you can use Create React App for a React-based project:
    • Run: npx create-react-app my-dark-mode-app
    • Navigate to the project directory: cd my-dark-mode-app
  • Install the Supabase client library by running: npm install @supabase/supabase-js

 
Step 3: Initialize Supabase
 

  • Create a file named supabaseClient.js in the src directory.
  • Initialize the Supabase client in this file:
  • 
    import { createClient } from '@supabase/supabase-js';
    
    

    const supabaseUrl = process.env.REACT_APP_SUPABASE_URL;
    const supabaseAnonKey = process.env.REACT_APP_SUPABASE_ANON_KEY;

    export const supabase = createClient(supabaseUrl, supabaseAnonKey);


  • Make sure to add your Supabase URL and API Key in your environment variables (e.g., create a .env file).

 
Step 4: Create a Dark Mode Toggle
 

  • In your React app, create a button or toggle switch that will allow users to switch between dark mode and light mode.
  • In the component containing the toggle, manage the state for dark mode:
  • 
    import React, { useState, useEffect } from 'react';
    
    

    const DarkModeToggle = () => {
    const [darkMode, setDarkMode] = useState(false);

    useEffect(() => {
    const storedPreference = localStorage.getItem('darkMode');
    if (storedPreference) {
    setDarkMode(JSON.parse(storedPreference));
    }
    }, []);

    useEffect(() => {
    localStorage.setItem('darkMode', darkMode);
    document.body.classList.toggle('dark-mode', darkMode);
    }, [darkMode]);

    return (
    <button onClick={() => setDarkMode(prevMode => !prevMode)}>
    {darkMode ? 'Switch to Light Mode' : 'Switch to Dark Mode'}

    );
    };

    export default DarkModeToggle;

 
Step 5: Style Your App
 

  • Define dark mode CSS styles. For example, in your App.css:
  • 
    body.dark-mode {
      background-color: #121212;
      color: #ffffff;
    }
    
      
  • Ensure your component and other elements account for dark mode styling. This could be done via CSS variables or additional class-based styles.

 
Step 6: Persist Dark Mode Choice Using Supabase
 

  • To offer a more seamless user experience, store the dark mode preference in Supabase for authenticated users.
  • First, set up authentication in Supabase if you haven't already.
  • Add logic to store dark mode preference in Supabase whenever it is toggled:
  • 
    import { supabase } from './supabaseClient';
    import { useEffect, useState } from 'react';
    
    

    const DarkModeToggle = () => {
    const [darkMode, setDarkMode] = useState(false);
    const user = supabase.auth.user();

    useEffect(() => {
    const fetchPreference = async () => {
    if (user) {
    const { data, error } = await supabase
    .from('preferences')
    .select('dark_mode')
    .eq('user_id', user.id)
    .single();
    if (data) {
    setDarkMode(data.dark_mode);
    }
    }
    };
    fetchPreference();
    }, [user]);

    useEffect(() => {
    const updatePreference = async () => {
    if (user) {
    await supabase
    .from('preferences')
    .upsert({ user_id: user.id, dark_mode: darkMode }, { onConflict: ['user_id'] });
    }
    };
    updatePreference();
    document.body.classList.toggle('dark-mode', darkMode);
    }, [darkMode, user]);

    return (
    <button onClick={() => setDarkMode(prevMode => !prevMode)}>
    {darkMode ? 'Switch to Light Mode' : 'Switch to Dark Mode'}

    );
    };

    export default DarkModeToggle;


  • Ensure Supabase has a table named preferences with columns user_id and dark_mode.

 
Step 7: Test Your Implementation
 

  • Ensure you test the dark mode toggle both logged in and logged out states.
  • Verify that the dark mode preference is correctly stored and retrieved from Supabase for authenticated users.
  • Check that the local storage functions as a fallback for unauthenticated users.

 

Why are companies choosing Bootstrapped?

40-60%

Faster with no-code

Nocode tools allow us to develop and deploy your new application 40-60% faster than regular app development methods.

90 days

From idea to MVP

Save time, money, and energy with an optimized hiring process. Access a pool of experts who are sourced, vetted, and matched to meet your precise requirements.

1 283 apps

built by our developers

With the Bootstrapped platform, managing projects and developers has never been easier.

hero graphic

Our capabilities

Bootstrapped offers a comprehensive suite of capabilities tailored for startups. Our expertise spans web and mobile app development, utilizing the latest technologies to ensure high performance and scalability. The team excels in creating intuitive user interfaces and seamless user experiences. We employ agile methodologies for flexible and efficient project management, ensuring timely delivery and adaptability to changing requirements. Additionally, Bootstrapped provides continuous support and maintenance, helping startups grow and evolve their digital products. Our services are designed to be affordable and high-quality, making them an ideal partner for new ventures.

Engineered for you

1

Fast Development: Bootstrapped specializes in helping startup founders build web and mobile apps quickly, ensuring a fast go-to-market strategy.

2

Tailored Solutions: The company offers customized app development, adapting to specific business needs and goals, which ensures your app stands out in the competitive market.

3

Expert Team: With a team of experienced developers and designers, Bootstrapped ensures high-quality, reliable, and scalable app solutions.

4

Affordable Pricing: Ideal for startups, Bootstrapped offers cost-effective development services without compromising on quality.

5

Supportive Partnership: Beyond development, Bootstrapped provides ongoing support and consultation, fostering long-term success for your startup.

6

Agile Methodology: Utilizing agile development practices, Bootstrapped ensures flexibility, iterative progress, and swift adaptation to changes, enhancing project success.

Yes, if you can dream it, we can build it.