Sure! Let's enhance your React application by adding a new element that also consumes the ThemeContext. For demonstration purposes, we'll add a SubHeadline component that changes its appearance based on the current theme.
Here's the updated code with the new SubHeadline component:
jsx
import React, { useState, createContext, useContext } from "react";
// Create ThemeContext outside of the App component to avoid recreating it on every render
const ThemeContext = createContext("");
export default function App() {
const ContextComponent = (): JSX.Element => {
const [theme, setTheme] = useState("dark");
// Optional: Define a toggleTheme function for cleaner code
const toggleTheme = () => {
setTheme(prevTheme => (prevTheme === "dark" ? "light" : "dark"));
};
return (
<ThemeContext.Provider value={theme}>
<div className={`app-container ${theme}`}>
<button onClick={toggleTheme}>
Toggle theme
</button>
<Headline />
<SubHeadline /> {/* New Element Added */}
</div>
</ThemeContext.Provider>
);
};
const Headline = (): JSX.Element => {
const theme = useContext(ThemeContext);
return <h1 className={`headline ${theme}`}>Current theme: {theme}</h1>;
};
// New SubHeadline Component
const SubHeadline = (): JSX.Element => {
const theme = useContext(ThemeContext);
return (
<h2 className={`subheadline ${theme}`}>
{theme === "dark" ? "Dark mode is active" : "Light mode is active"}
</h2>
);
};
return <ContextComponent />;
}
Explanation of the Changes
Move ThemeContext Outside of App:
Why? Creating the context outside prevents it from being recreated on every render, which can lead to performance issues and unnecessary re-renders of consuming components.
Added SubHeadline Component:
Purpose: This new component also consumes the ThemeContext to display a message based on the current theme.
By adding the SubHeadline component, you've demonstrated how multiple components can consume the same context, allowing for consistent theming across your application. This approach promotes scalability and maintainability, especially as your application grows.
Feel free to customize the new component further or add additional elements that utilize ThemeContext to enhance your application's functionality and user experience!