fix: Resolve infinite render loop by memoizing context functions and values
This commit is contained in:
@@ -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>
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user