React State Management: Context API vs. Redux & Building a Theme Switcher
A practical comparison of React Context and Redux Toolkit: what each one actually does, how each decides which components re-render, and when the extra setup of Redux pays off. You then build a dark mode switcher with Context, a custom useTheme hook, localStorage and Tailwind's class-based dark variant, plus the same toggle in Redux Toolkit for comparison.

Sooner or later a React app has data that many components need, such as the signed-in user or the color theme. This guide helps you choose between React's built-in Context and Redux for that data, and shows the reasoning behind the choice. Then you'll build a dark mode switcher with Context and a custom hook, and see the same toggle in Redux Toolkit so you can compare the two.
This is part 21 of the Frontend & JavaScript Fundamentals series. It builds on custom hooks and the useForm example, because the theme switcher ends in a custom hook too.
Key takeaways
- Context passes a value down the tree; it doesn't manage state. You still hold the state with
useStateoruseReducer. - Every component that reads a context re-renders when its value changes. With Redux's
useSelector, store updates re-render a component only when its selected piece changes. - A theme changes rarely and is read in many places, so Context fits it well. Redux pays off for large, frequently updated, shared state.
What each tool actually does
React Context is a way to pass a value to every component below a provider without threading it through props. React 16.3 introduced the current version of the API, and the useContext hook reads it. Mark Erikson, a Redux maintainer, describes Context as a form of dependency injection: a transport for a value, not a state manager. The value usually comes from useState or useReducer in a parent component.
Redux is a store that holds state outside your components. You change it by dispatching actions, and reducers decide the new state. The Redux docs call Redux Toolkit the official, recommended way to write Redux code. Its configureStore also sets up the Redux DevTools extension, which lets you trace each change back to the action that caused it.
How each one decides what re-renders
This is the difference that matters most in practice.
- Context: the
useContextdocs say React re-renders every component that reads the context when the provider gets a different value. Wrapping a consumer inmemodoesn't prevent this. - Redux: the React Redux docs say
useSelectorcompares the old and new selected values with===after each dispatched action. A store update re-renders the component only when they differ. It still re-renders when its parent does.
So with one big context, a change to any part of the value re-renders every reader. With Redux, a component that selects only the theme ignores changes to everything else.
When to use which
The Redux FAQ says Redux is most useful when you have a lot of state needed in many places, the state updates often, the update logic is complex, the codebase is medium or large with many people working on it, or you need to see how the state changed over time. It also quotes Dan Abramov, one of its creators: "don't use Redux until you have problems with vanilla React."
| Option | What it does | Trade-off | Use it when |
|---|---|---|---|
| Props | Passes data one level at a time | Gets tedious through many layers | The data is used close to where it lives |
Context + useState or useReducer |
Passes a value to any depth | Every reader re-renders on each change | Values that change rarely: theme, locale, signed-in user |
| Redux Toolkit | A central store with actions and selectors | More concepts, a dependency and more code | Large, often-updated shared state you want to trace |
As a rule of thumb: if your only problem is passing values through many layers of props, use Context. Erikson's article gives the same advice. If you need fine-grained re-renders, a trace of every change, or several contexts that depend on each other, look at Redux Toolkit.
Build a theme switcher with Context
A theme is a good fit for Context. It changes only when the user clicks, almost every component may care about it, and there's no complex update logic. You need three pieces:
- A context that carries the value.
- A provider that holds the state and applies the theme to the page.
- A hook that reads the context and fails loudly if the provider is missing.
Step 1: Create the context, provider and hook
Put this in src/context/ThemeContext.jsx.
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
// null default: useTheme can tell when there is no provider above it
const ThemeContext = createContext(null);
function getInitialTheme() {
return localStorage.getItem('app-theme') === 'dark' ? 'dark' : 'light';
}
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState(getInitialTheme);
useEffect(() => {
document.documentElement.classList.toggle('dark', theme === 'dark');
localStorage.setItem('app-theme', theme);
}, [theme]);
const toggleTheme = useCallback(() => {
setTheme((prev) => (prev === 'light' ? 'dark' : 'light'));
}, []);
const value = useMemo(() => ({ theme, toggleTheme }), [theme, toggleTheme]);
return <ThemeContext value={value}>{children}</ThemeContext>;
}
export function useTheme() {
const context = useContext(ThemeContext);
if (!context) {
throw new Error('useTheme must be used within a ThemeProvider');
}
return context;
}
Checked against react@19.3.1, @reduxjs/toolkit@2.13.0 and react-redux@9.3.1, 2026-10-29.
Three details are worth a closer look.
The default value is null. The createContext docs say the default is only used when no provider is found above the component. If you pass a real default such as { theme: 'light' }, the check in useTheme can never fire.
// Avoid: a component outside the provider silently gets a toggle that does nothing
const ThemeContext = createContext({ theme: 'light', toggleTheme: () => {} });
// Better: no provider means null, and useTheme throws a clear error
const ThemeContext = createContext(null);
The value is memoized. Without useMemo, { theme, toggleTheme } is a new object on every render of the provider. The useContext docs show that this re-renders every reader even when nothing changed. useMemo and useCallback keep the same object until theme changes.
// Avoid: a new object each render, so every reader re-renders
return <ThemeContext value={{ theme, toggleTheme }}>{children}</ThemeContext>;
// Better: the same object until theme changes
const value = useMemo(() => ({ theme, toggleTheme }), [theme, toggleTheme]);
return <ThemeContext value={value}>{children}</ThemeContext>;
The provider is the context itself. The createContext docs say that from React 19 you can render <ThemeContext> as the provider. <ThemeContext.Provider> is the older form, and you need it on React 18 and below.
Step 2: Wrap the app
Wrap your root component once, in src/main.jsx or src/index.js.
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import { ThemeProvider } from './context/ThemeContext';
import './index.css';
createRoot(document.getElementById('root')).render(
<StrictMode>
<ThemeProvider>
<App />
</ThemeProvider>
</StrictMode>
);
Step 3: Add the toggle
Any component below the provider can now read the theme without props. Save this as src/Header.jsx, next to the context folder.
import { useTheme } from './context/ThemeContext';
export default function Header() {
const { theme, toggleTheme } = useTheme();
return (
<header className="flex items-center justify-between bg-white p-4 dark:bg-gray-900">
<h1 className="text-xl font-bold text-gray-900 dark:text-white">DevPortfolio</h1>
<button
type="button"
onClick={toggleTheme}
aria-pressed={theme === 'dark'}
className="rounded-full bg-gray-200 px-3 py-2 dark:bg-gray-700 dark:text-white"
>
Dark mode
</button>
</header>
);
}
The button keeps one label and uses aria-pressed, so screen readers announce it as a toggle that is on or off.
Step 4: Make Tailwind follow the class
The Tailwind docs say the dark: variant follows the system setting (prefers-color-scheme) by default. To switch it with a class instead, add a custom variant to your main CSS file.
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));
Now dark:bg-gray-900 applies whenever <html> has the dark class, which the provider's effect adds.
Step 5: Avoid the flash on first load
The provider reads localStorage during its first render, in the state initializer. But effects run after the browser paints, so a dark-mode user still sees the light page for a moment. The Tailwind docs recommend setting the class with a small inline script in <head>, before the page draws.
<script>
if (localStorage.getItem('app-theme') === 'dark') {
document.documentElement.classList.add('dark');
}
</script>
Server rendering
This setup assumes the app renders in the browser, as a Vite app does. With server rendering, as in Next.js, localStorage doesn't exist on the server, and the server's theme may not match the browser's. Keep the inline script, and read the saved theme in an effect or with your framework's theme helper.
The earlier version of this post said that reading localStorage in the state initializer prevents the flash, and that the useTheme check caught a missing provider. Neither was true; the code above fixes both.
Keep contexts small
Because every reader re-renders when the value changes, avoid one context for unrelated data. If the theme, the user and a notification count share one object, a new notification re-renders the theme toggle too.
// Avoid: one context, so a new notification re-renders every theme reader
<AppContext value={{ theme, user, notifications }}>
<App />
</AppContext>
// Better: separate contexts, each with its own readers
<ThemeContext value={themeValue}>
<NotificationsContext value={notificationsValue}>
<App />
</NotificationsContext>
</ThemeContext>
For data that changes many times a second, or when you need more than a few related contexts, Erikson's article suggests that Redux becomes the better tool.
The same toggle in Redux Toolkit
For comparison, here is the theme as a Redux Toolkit slice. createSlice generates the action, and the Redux Toolkit docs explain that Immer turns the "mutating" line into a new state object.
// src/themeSlice.js
import { configureStore, createSlice } from '@reduxjs/toolkit';
const themeSlice = createSlice({
name: 'theme',
initialState: { value: 'light' },
reducers: {
toggled(state) {
// Immer turns this "mutation" into a new state object
state.value = state.value === 'light' ? 'dark' : 'light';
},
},
});
export const { toggled } = themeSlice.actions;
export const store = configureStore({ reducer: { theme: themeSlice.reducer } });
A component in src/ReduxToggle.jsx reads the value with useSelector and changes it with dispatch. The app needs <Provider store={store}> from react-redux around it.
import { useDispatch, useSelector } from 'react-redux';
import { toggled } from './themeSlice';
export function ReduxToggle() {
const theme = useSelector((state) => state.theme.value);
const dispatch = useDispatch();
return <button onClick={() => dispatch(toggled())}>Theme: {theme}</button>;
}
It works, but you still need the effect, the localStorage code and the inline script from above. For a theme alone, that's two extra packages for the same result. Redux earns its place when many slices of state, frequent updates and DevTools tracing come together.
Next in the series, navigation and data flow patterns looks at how data moves between pages and routes.
Frequently asked questions
Is the Context API a replacement for Redux?
Only for some jobs. Context passes a value down the tree, and you still manage the state with useState or useReducer. Redux adds a central store, actions, selectors with fine-grained re-renders and DevTools tracing. If all you need is to avoid prop drilling, Context is enough.
Does Context cause performance problems?
It can. The React docs say every component that reads a context re-renders when the provider's value changes, and memo doesn't stop it. Memoize the value with useMemo and split unrelated data into separate contexts. For values that change many times a second, a store with selectors is usually a better fit.
Why does my useTheme error never fire?
Check the default value you passed to createContext. React uses it whenever no provider is found, so a non-empty default hides the missing provider. Pass null and throw in the hook when the value is null.
What about Zustand or Jotai?
They are other state libraries. The Redux FAQ notes that many tools solve some of the same problems Redux does, and this post doesn't compare them. As a rule of thumb, the same question applies: pick a store when Context's "every reader re-renders" behavior or your update logic becomes the problem.
Why does my page flash light before switching to dark?
Effects run after the first paint, so the class arrives too late. Add the inline script from Step 5 to <head>, as the Tailwind docs recommend. It sets the class before the page is drawn.
Sources
Verified against the sources below on October 29, 2026. Products and docs change often: check the linked sources if something looks different.
- React docs: useContext
- React docs: createContext
- React blog: React v16.3.0 (new context API)
- Redux FAQ: When should I use Redux?
- Redux docs: Getting Started
- Redux Toolkit: Quick Start
- React Redux docs: Hooks (useSelector)
- Mark Erikson (Redux maintainer): Why React Context is Not a State Management Tool
- Tailwind CSS docs: Dark mode
All 30 parts in this series
- Part 01Overcoming the Daunting Start: A Strategic Roadmap for New Frontend Developers
- Part 02Beyond the Tags: Mastering HTML Architecture for Product-Based Roles
- Part 03From Selectors to BEM: CSS Concepts You Must Know for Professional Projects
- Part 04Mastering the Primitives: A Builder's Guide to JavaScript Data Types and Functions
- Part 05Demystifying Scope and Closure: Key Concepts for Writing Robust JavaScript
- Part 06Beyond Frameworks: Practical DOM Manipulation Techniques for High-Performance UIs
- Part 07From Prototypes to ES6 Classes: Understanding JavaScript's Object-Oriented Nature
- Part 08Architecting Scalable JavaScript: OOP Principles & Design Patterns
- Part 09Mastering the Metal: Essential Web APIs & Browser Internals for Frontend Engineers
- Part 10Understanding the JavaScript Runtime: Event Loop, Call Stack, and Task Queue Explained
- Part 11Mastering Asynchronous Operations with JavaScript Promises: A Builder's Guide
- Part 12Modern Async Patterns: Making Asynchronous Code Readable with Async/Await and Generators
- Part 13Inside the V8 Engine: A Deep Dive into JavaScript Execution
- Part 14Demystifying CORS, HTTP, and Security: A Builder’s Guide
- Part 15REST vs. GraphQL: A Frontend Engineer’s Reality Check
- Part 16Secure Frontend Auth: The Definitive Guide to JWTs, Cookies, and Storage Strategies
- Part 17Why TypeScript Matters: Adding Type Safety to Your JavaScript Projects
- Part 18Getting Started with React: Deconstructing JSX and Component Architecture
- Part 19React Architecture: Mastering State and Props in Class vs. Functional Components
- Part 20Mastering React Hooks: From useState to Building a Production-Ready Custom Hook
- Part 21React State Management: Context API vs. Redux & Building a Theme Switcher
- Part 22React Architecture: Advanced Navigation and Data Flow Patterns
- Part 23Automated Testing in React: Unit Testing with Jest and React Testing Library
- Part 24Mastering Chrome DevTools: Debugging Techniques That Save Hours of Development Time
- Part 25Automating Code Quality: The Modern Stack with ESLint, Prettier, and Husky
- Part 26Demystifying the Build Pipeline: A Deep Dive into Webpack and Babel Configuration
- Part 27Improving Performance with Server-Side Rendering: Concepts and Implementation
- Part 28From Development to Production: A Builder's Guide to Frontend Deployment Strategies
- Part 29Introduction to Micro Frontends: Building Scalable Architectures
- Part 30The Frontend Architecture: From Junior Developer to Tech Lead
AI Automation Engineer & Salesforce Developer
Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.



Comments
Loading comments...