Dynamic Configuration Changes with TanStack Config in a React App
Illustrate how to modify application configurations dynamically in response to user actions, using TanStack Config in a React application.
import { useConfig } from 'tanstack-config-react';
function ThemeToggler() {
const [config, setConfig] = useConfig();
const toggleTheme = () => {
setConfig({
...config,
theme: config.theme === 'dark' ? 'light' : 'dark',
});
};
return (
<button onClick={toggleTheme}>Toggle Theme</button>
);
}
This code demonstrates how to toggle between dark and light themes in a React application using TanStack Config. On pressing the button, it switches the theme configuration between 'dark' and 'light'. 'useConfig' hook from TanStack Config is used to access and update the application's configuration dynamically.
import { ConfigProvider } from 'tanstack-config-react';
function App() {
const initialConfig = { theme: 'dark' };
return (
<ConfigProvider config={initialConfig}>
<ThemeToggler />
</ConfigProvider>
);
}
This snippet wraps the application, or a part of it, in a ConfigProvider from TanStack Config. It initializes the application with a default configuration, setting the theme to 'dark'. The ThemeToggler component, as defined in the previous snippet, can then dynamically update this configuration.