fix: Resolve infinite render loop by memoizing context functions and values

This commit is contained in:
Yunxiao Xu
2026-02-17 02:43:19 -08:00
parent 23471350df
commit 1b15a4e18c
2 changed files with 40 additions and 26 deletions

View File

@@ -1,4 +1,4 @@
import { createContext, useContext, useEffect, useState } from "react"
import { createContext, useContext, useEffect, useState, useCallback, useMemo } from "react"
import { AuthService } from "@/services/auth"
export type Theme = "light" | "dark"
@@ -29,7 +29,7 @@ export function ThemeProvider({
root.classList.add(theme)
}, [theme])
const setTheme = async (newTheme: Theme) => {
const setTheme = useCallback(async (newTheme: Theme) => {
setThemeState(newTheme)
if (isAuthenticated) {
try {
@@ -38,18 +38,25 @@ export function ThemeProvider({
console.error("Failed to sync theme to backend:", error)
}
}
}
}, [isAuthenticated])
const setThemeLocal = (newTheme: Theme) => {
const setThemeLocal = useCallback((newTheme: Theme) => {
setThemeState(newTheme)
}
}, [])
const toggleTheme = () => {
const toggleTheme = useCallback(() => {
setTheme(theme === "light" ? "dark" : "light")
}
}, [theme, setTheme])
const value = useMemo(() => ({
theme,
setTheme,
setThemeLocal,
toggleTheme
}), [theme, setTheme, setThemeLocal, toggleTheme])
return (
<ThemeContext.Provider value={{ theme, setTheme, setThemeLocal, toggleTheme }}>
<ThemeContext.Provider value={value}>
{children}
</ThemeContext.Provider>
)