useState->useRef

Signed-off-by: Timo K <toger5@hotmail.de>
This commit is contained in:
Timo K
2024-02-22 15:19:25 +01:00
parent 2949ab0302
commit a886457462

View File

@@ -14,22 +14,20 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import { useLayoutEffect, useState } from "react"; import { useLayoutEffect, useRef } from "react";
import { useUrlParams } from "./UrlParams"; import { useUrlParams } from "./UrlParams";
export const useTheme = (): void => { export const useTheme = (): void => {
const { theme: themeName } = useUrlParams(); const { theme: themeName } = useUrlParams();
const [previousTheme, setPreviousTheme] = useState<string | null>( const previousTheme = useRef<string | null>(document.body.classList.item(0));
document.body.classList.item(0),
);
useLayoutEffect(() => { useLayoutEffect(() => {
// Don't update the current theme if the url does not contain a theme prop. // Don't update the current theme if the url does not contain a theme prop.
if (!themeName) return; if (!themeName) return;
const theme = themeName.includes("light") ? "light" : "dark"; const theme = themeName.includes("light") ? "light" : "dark";
const themeHighContrast = themeName.includes("high-contrast") ? "-hc" : ""; const themeHighContrast = themeName.includes("high-contrast") ? "-hc" : "";
const themeString = "cpd-theme-" + theme + themeHighContrast; const themeString = "cpd-theme-" + theme + themeHighContrast;
if (themeString !== previousTheme) { if (themeString !== previousTheme.current) {
document.body.classList.remove( document.body.classList.remove(
"cpd-theme-light", "cpd-theme-light",
"cpd-theme-dark", "cpd-theme-dark",
@@ -37,7 +35,7 @@ export const useTheme = (): void => {
"cpd-theme-dark-hc", "cpd-theme-dark-hc",
); );
document.body.classList.add(themeString); document.body.classList.add(themeString);
setPreviousTheme(themeString); previousTheme.current = themeString;
} }
}, [previousTheme, themeName]); }, [previousTheme, themeName]);
}; };