Certainly! It's possible to create a ThemeContext without using useMemo. However, please note that useMemo is often used for performance optimizations to avoid unnecessary re-renders. If you don't use useMemo for context values, and those values change frequently, it could potentially lead to performance issues in larger applications.
Here's how you would set up ThemeContext without useMemo:
// ThemeContext.js
import React, { createContext, useState, useContext } from 'react';
const ThemeContext = createContext(null);
export function useTheme() {
return useContext(ThemeContext);
}
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
const toggleTheme = () => {
setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));
};
// Simple logic to determine the Bootstrap class based on the theme
const themeClass = theme === 'dark' ? 'bg-dark text-white' : 'bg-light text-dark';
return (
<ThemeContext.Provider value={{ theme, toggleTheme, themeClass }}>
{children}
</ThemeContext.Provider>
);
}
Then, you wrap your application root component in the ThemeProvider from your context file. Here's an example for index.js:
// index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import { ThemeProvider } from './ThemeContext';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<ThemeProvider>
<App />
</ThemeProvider>
</React.StrictMode>
);
Now you can use the useTheme hook to consume the context in your components.
For the theme toggle button:
// ThemeToggleButton.js
import React from 'react';
import { useTheme } from './ThemeContext';
import { Button } from 'react-bootstrap';
function ThemeToggleButton() {
const { toggleTheme } = useTheme();
return (
<Button onClick={toggleTheme} variant="primary">
Toggle Theme
</Button>
);
}
export default ThemeToggleButton;
For a component that should be styled based on the theme:
// ThemedContent.js
import React from 'react';
import { useTheme } from './ThemeContext';
function ThemedContent() {
const { themeClass } = useTheme();
return (
<div className={`p-3 ${themeClass}`}>
<h1>This is a themed content</h1>
</div>
);
}
export default ThemedContent;
By removing useMemo, every time the context's state updates, the context value object will be recreated, which could cause unnecessary re-renders. If your app is relatively small or these context state updates are infrequent, you may not see a noticeable impact, but it's something to keep an eye on as your application scales.