Centralizing Application Settings with TanStack Config
Demonstrate how to create a centralized configuration for application settings (e.g., theme, API endpoints) using TanStack Config and access them across React components.
import { createConfig } from '@tanstack/config';
export const appConfig = createConfig({
// Define default configuration
defaultConfig: {
apiBaseUrl: 'https://api.example.com',
theme: 'light'
}
});
This code snippet creates a centralized configuration for the application using TanStack Config. It defines default configuration settings such as the API base URL and the application's theme.
import React, { createContext, useContext } from 'react';
import { appConfig } from './appConfig';
export const ConfigContext = createContext();
export const ConfigProvider = ({ children }) => (
<ConfigContext.Provider value={appConfig.getCurrentConfig()}>
{children}
</ConfigContext.Provider>
);
This snippet sets up a React context for the application configuration. It exports a ConfigProvider component that makes the current configuration accessible to any component in the component tree that uses the ConfigContext.
import React, { useContext } from 'react';
import { ConfigContext } from './ConfigContext';
function App() {
const config = useContext(ConfigContext);
return (
<div>
<h1>App Theme: {config.theme}</h1>
<p>API Base URL: {config.apiBaseUrl}</p>
</div>
);
}
export default App;
In this example, a React component named App uses the useContext hook to access the application's configuration through the ConfigContext. It then renders the theme and API base URL defined in the configuration.