Dark Mode Toggle in React

 ๐ŸŒ™ Dark Mode Toggle in React (Step-by-Step)

✅ 1. Basic Setup with React Hooks

We’ll use useState and optionally useEffect to toggle between light and dark themes.


App.js

jsx

Copy

Edit

import React, { useState, useEffect } from 'react';

import './App.css';


function App() {

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


  // Optional: Save user preference in localStorage

  useEffect(() => {

    const savedMode = localStorage.getItem('darkMode') === 'true';

    setDarkMode(savedMode);

  }, []);


  useEffect(() => {

    localStorage.setItem('darkMode', darkMode);

  }, [darkMode]);


  const toggleDarkMode = () => {

    setDarkMode(prevMode => !prevMode);

  };


  return (

    <div className={darkMode ? 'app dark-mode' : 'app'}>

      <h1>Dark Mode Toggle in React</h1>

      <button onClick={toggleDarkMode}>

        Switch to {darkMode ? 'Light' : 'Dark'} Mode

      </button>

    </div>

  );

}


export default App;

✅ 2. Styling with CSS

App.css

css

Copy

Edit

/* Light mode (default) */

.app {

  background-color: #f5f5f5;

  color: #222;

  text-align: center;

  padding: 2rem;

  min-height: 100vh;

  transition: all 0.3s ease;

}


button {

  padding: 0.5rem 1rem;

  font-size: 1rem;

  margin-top: 1rem;

}


/* Dark mode styles */

.dark-mode {

  background-color: #121212;

  color: #ffffff;

}

๐Ÿง  Bonus Features (Optional)

Use CSS variables for theme colors


Add animation for smoother transitions


Sync with system preferences using window.matchMedia


Use a context provider for global theme management


✅ Summary

useState handles the toggle logic


localStorage keeps the mode persistent


CSS applies the light and dark themes

Learn MERN Stack Course in Hyderabad

Read More

Lazy Loading Components in React

React State Management Best Practices

๐ŸŽจ Frontend (React Focused)

Building a File Upload API in MERN

Visit Our Quality Thought Training in Hyderabad

Get Directions

Comments

Popular posts from this blog

Understanding Snowflake Editions: Standard, Enterprise, Business Critical

Installing Tosca: Step-by-Step Guide for Beginners

Why Data Science Course?