T
TanStack2y ago
fascinating-indigo

Can't modify router context from within a component

I don't know if this is intentional or not but I cannot modify context from within a component App.tsx
const router = createRouter({
routeTree,
context: {
user: null,
darkMode: false,
setDarkMode: () => {}
}
});

export default function App() {
const [user, setUser] = useState<User | null>(null);
const [darkMode, setDarkMode] = useState<boolean>(false);

useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(user => setUser(user));
return () => unsubscribe();
}, []);

return <RouterProvider router={router} context={{ user, darkMode, setDarkMode }} />;
}
const router = createRouter({
routeTree,
context: {
user: null,
darkMode: false,
setDarkMode: () => {}
}
});

export default function App() {
const [user, setUser] = useState<User | null>(null);
const [darkMode, setDarkMode] = useState<boolean>(false);

useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(user => setUser(user));
return () => unsubscribe();
}, []);

return <RouterProvider router={router} context={{ user, darkMode, setDarkMode }} />;
}
index.tsx
function Page() {
const { darkMode, setDarkMode } = Route.useRouteContext();

return (
<>
<h1>Theme is {darkMode ? "dark" : "light"}</h1>
<button onClick={() => setDarkMode(!darkMode)}>Toggle</button>
</>
);
}
function Page() {
const { darkMode, setDarkMode } = Route.useRouteContext();

return (
<>
<h1>Theme is {darkMode ? "dark" : "light"}</h1>
<button onClick={() => setDarkMode(!darkMode)}>Toggle</button>
</>
);
}
Even when I click the button the darkMode remains the same (i.e false)
4 Replies
fascinating-indigo
fascinating-indigoOP2y ago
Okay, so I did some testing with the devtools and on the initial click the devtools toggle correctly but get stuck at true after that while on the console it continues to be false
fascinating-indigo
fascinating-indigoOP2y ago
fascinating-indigo
fascinating-indigoOP2y ago
So using a functional update (setDarkMode(prev => !prev)) seems to toggle correctly between states in the devtools but the darkMode var remains the same
fascinating-indigo
fascinating-indigoOP2y ago

Did you find this page helpful?