Note This pattern provides Redux-like state management with built-in React APIs. Splitting state and dispatch into separate contexts prevents components that only dispatch actions from re-rendering when state changes.
// Create -> Provide -> ConsumeconstCtx=createContext(defaultValue);<Ctx.Provider value={value}>...const value =useContext(Ctx);
Example
// Locale context for internationalizationconstLocaleContext=createContext('en');functionLocaleProvider({ children }){const[locale, setLocale]=useState('en');const translations =useMemo(()=>loadTranslations(locale),[locale]);const value =useMemo(()=>({ locale, setLocale, t:(key)=> translations[key]|| key }),[locale, translations]);return(<LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>);}functionuseLocale(){returnuseContext(LocaleContext);}// Usage in any componentfunctionWelcomeBanner(){const{ t, locale }=useLocale();return<h1>{t('welcome_message')}({locale})</h1>;}
Note Context is ideal for low-frequency updates like theme, locale, and auth. For high-frequency updates (e.g., mouse position), context can cause excessive re-renders -- consider useSyncExternalStore or a dedicated state library.
Frequently asked questions
How does React handle context state management?
React covers this with 2 copy-ready snippets on this page. The "Context + Reducer Pattern" snippet in React uses `const StateCtx = createContext(null);`.
Which code does the React example use?
The "Context + Reducer Pattern" snippet uses `const StateCtx = createContext(null);`, from the Patterns section of the React cheat sheet.
What other React snippets are shown for "context state management"?
Besides "Context + Reducer Pattern", this page also shows "Context for Global State".
Is there anything to watch out for?
Yes. For "Context + Reducer Pattern": This pattern provides Redux-like state management with built-in React APIs. Splitting state and dispatch into separate contexts prevents components that only dispatch actions from re-rendering when state changes.