This is a simple theme toggle application built with Vite and React. The app allows users to switch between light and dark themes, and it uses the Context API to manage the global theme state. The theme preference is saved in localStorage to persist between sessions.
- Toggle between light and dark themes.
- Theme state is managed globally using the Context API.
- Theme preference is saved in
localStorage. - Smooth transitions between themes.
Make sure you have the following installed on your system:
-
Clone the Repository:
git clone https://github.com/your-username/theme-toggle-app.git cd theme-toggle-app -
Install Dependencies:
npm install
-
Run the Development Server:
npm run dev
-
Build for Production:
npm run build
- Clone the repository and navigate to the project directory.
- Run the development server to view the app on
localhost. - Use the toggle button to switch between light and dark themes.
The ThemeContext.js file is used to create a context for the theme state. This allows any component in the application to access and modify the theme state without passing props.
import React, { createContext, useState, useEffect } from "react";
// Create Context
export const ThemeContext = createContext();
// Provider Component
export const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState("light");
useEffect(() => {
const savedTheme = localStorage.getItem("theme");
if (savedTheme) {
setTheme(savedTheme);
}
}, []);
useEffect(() => {
localStorage.setItem("theme", theme);
}, [theme]);
const toggleTheme = () => {
setTheme((prevTheme) => (prevTheme === "light" ? "dark" : "light"));
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
};Contributions are welcome! Please feel free to submit a Pull Request or open an issue.
This project is licensed under the MIT License.