Context & State ManagementBeginner
1Question 1 of 1
javascriptHow does React Context API work and how does it compare to Redux or Zustand?
Explanation & Concept
The Context API provides a way to share data through the component tree without passing props manually down every level (prop drilling).
• Context: Ideal for low-frequency global state (themes, authenticated user profile, localization). • State Management Libraries (Zustand, Redux): Better for high-frequency, complex state updates because Context re-renders **all consumers** whenever its value changes, whereas Zustand supports fine-grained selector subscriptions.
Code Example
javascript
import { createContext, useContext, useState } from "react";
const ThemeContext = createContext();
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState("dark");
const toggleTheme = () => setTheme((t) => (t === "dark" ? "light" : "dark"));
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
}
export function ThemeToggle() {
const { theme, toggleTheme } = useContext(ThemeContext);
return <button onClick={toggleTheme}>Current Theme: {theme}</button>;
}How It Works & Key Takeaways
Wrapping the app with `ThemeProvider` enables any deeply nested child component to access theme state directly with `useContext(ThemeContext)`.
Mock Test · 1 Questions · Optional
Ready for Virtual DOM & Reconciliation?
Take a quick test to evaluate yourself, or move straight to the next module.
Beginner1 questions