Changing image theme using localStorage need to refresh to get work
Unanswered
Fire ant posted this in #help-forum
Fire antOP
"use client";
import React, { useEffect, useState } from "react";
import Image from "next/image";
import Link from "next/link";
export default function Logo() {
const [theme, setTheme] = useState("light");
useEffect(() => {
// Get theme from localStorage
const storedTheme = localStorage.getItem("theme");
if (storedTheme) {
setTheme(storedTheme);
} else {
const systemTheme = window.matchMedia("(prefers-color-scheme: dark)")
.matches
? "dark"
: "light";
setTheme(systemTheme);
}
}, []);
return (
<Link href="/">
<Image
className="mb-8 object-cover h-auto"
src={
theme === "light"
? "/static/img/logo-white.webp"
: "/static/img/logo-dark.webp"
}
alt="Logo"
width={450}
height={150}
/>
</Link>
);
}I need to refresh the page to see the image changes, using
router.refresh() also not work.Any recommended method? On toggle mode i use
next/themes to change layout themes