Trigger useEffect when color mode changes
Unanswered
English Lop posted this in #help-forum
English LopOP
I am trying to trigger a useEffect any time my application’s theme color changes. However, the useEffect is not running when there is a change to ColorMode.
Here is my component:
Here is my component:
"use client";
import React, { useState, useEffect } from "react";
import useColorMode from "@/app/hooks/useColorMode";
import {
InteractiveDashboard,
MetabaseProvider,
defineEmbeddingSdkConfig,
defineEmbeddingSdkTheme,
} from "@metabase/embedding-sdk-react";
const config = defineEmbeddingSdkConfig({
...
});
const dashboardId = 2089;
export default function MetabaseDashboard() {
const [colorMode] = useColorMode();
const [reloadKey, setReloadKey] = useState(0);
// Define the Metabase theme dynamically based on color mode
const theme = defineEmbeddingSdkTheme({
fontFamily: "Lato",
colors: {
brand: "#00C1FF",
filter: "#713AC9",
summarize: "#C25EFF",
charts: ["#00C1FF", "#C25EFF", "#713AC9", "#00E8CC"],
},
components: {
dashboard: {
backgroundColor: colorMode === "dark" ? "#1A202C" : "#f3f4f6",
card: {
backgroundColor: colorMode === "dark" ? "#1A202C" : "#f3f4f6",
},
},
question: {
backgroundColor: colorMode === "dark" ? "#1A202C" : "#f3f4f6",
},
},
});
// Increment the reload key whenever color mode changes
useEffect(() => {
console.log("Color mode changed:", colorMode);
setReloadKey((prev) => {
const newKey = prev + 1;
console.log("New reload key:", newKey); // Log the new key
return newKey;
});
}, [colorMode]);
return (
<MetabaseProvider config={config} theme={theme}>
<div className="dashboard-container">
<InteractiveDashboard
key={reloadKey} // Force reload of the dashboard
dashboardId={dashboardId}
withTitle={true}
withDownloads={true}
/>
</div>
</MetabaseProvider>
);
}
1 Reply
English LopOP
Here is my useColorMode hook:
import { useEffect } from "react";
import useLocalStorage from "./useLocalStorage";
const useColorMode = () => {
const [colorMode, setColorMode] = useLocalStorage("color-theme", "light");
useEffect(() => {
const className = "dark";
const bodyClass = window.document.documentElement.classList;
console.log("Setting color mode to:", colorMode);
colorMode === "dark"
? bodyClass.add(className)
: bodyClass.remove(className);
}, [colorMode]);
return [colorMode, setColorMode];
};
export default useColorMode;