DarkMode Context API
It enables to add dark mode switch.
1
First Create a file darkModeContext.jsx
in context
directory.
context/darkModeContext.jsx
import React, { useState, useContext, useEffect, createContext } from "react";
const DarkModeContext = createContext(undefined);
export function DarkModeProvider({ children }) {
const [isDarkMode, setDarkMode] = useState(false);
function updateTheme() {
const currentTheme = localStorage.getItem("isDarkMode") || "false";
if (currentTheme === "true") {
document.body.classList.add("dark");
} else {
document.body.classList.remove("dark");
}
}
useEffect(() => {
updateTheme();
}, []);
function changeDarkMode(value) {
localStorage.setItem("isDarkMode", value.toString());
setDarkMode(value);
updateTheme();
}
return (
<DarkModeContext.Provider value={{ isDarkMode, changeDarkMode }}>
{children}
</DarkModeContext.Provider>
);
}
export const useDarkMode = () => {
const context = useContext(DarkModeContext);
if (context === undefined) {
throw new Error("useAuth can only be used inside AuthProvider");
}
return context;
};
2
Wrap you app
I am using Next.js that's why I am adding DarkModeProvider
to _app.jsx
.
pages/_app.jsx
import "../styles/globals.css";
import Layout from "../layout/Layout";
import { DarkModeProvider } from "../context/darkModeContext";
function MyApp({ Component, pageProps }) {
return (
<DarkModeProvider>
<Layout>
<Component {...pageProps} />
</Layout>
</DarkModeProvider>
);
}
export default MyApp;
3
Use DarkMode
Install react-toggle-dark-mode to use the DarkModeSwitch
.
components/Navbar.jsx
// Other files.............
import { useDarkMode } from "../context/darkModeContext";
import { DarkModeSwitch } from "react-toggle-dark-mode"; // install this package
export default function TopNavbar() {
const { isDarkMode, changeDarkMode } = useDarkMode();
return (
<DarkModeSwitch
checked={isDarkMode}
onChange={changeDarkMode}
size={24}
/>
)
}