Using TanStack Config with React Context for Theme Management
Demonstrate creating a theme configuration using TanStack Config and leveraging React Context to provide theme settings throughout the application.
import { createContext, useContext, useMemo } from 'react';
const ThemeContext = createContext();
Import necessary hooks from React and create a context for the theme.
function ThemeProvider({ children, themeConfig }) {
const theme = useMemo(() => themeConfig, [themeConfig]);
return (
<ThemeContext.Provider value={theme}>
{children}
</ThemeContext.Provider>
);
}
Create a ThemeProvider component that uses useMemo to memoize the theme configuration and provides it through the created context.
function useTheme() {
const context = useContext(ThemeContext);
if (context === undefined) {
throw new Error('useTheme must be used within a ThemeProvider');
}
return context;
}
Define a custom hook useTheme for consuming the theme context, which ensures the hook is used within the ThemeProvider.
const themeConfig = {
colors: {
primary: '#007bff',
secondary: '#6c757d'
},
fontSize: {
small: '12px',
medium: '16px',
large: '20px'
}
};
Define a theme configuration object that can be customized based on requirements.
function App() {
return (
<ThemeProvider themeConfig={themeConfig}>
{/* Rest of the application */}
</ThemeProvider>
);
}
Wrap the application or components within the ThemeProvider and pass the themeConfig as prop to make the theme configuration available throughout the component tree.