Context is created with createContext(defaultValue), which returns an object with a Provider component used to supply an actual value further down the tree, and any descendant component can read that value with the useContext hook, regardless of how deeply nested it is. It's specifically designed for data that's genuinely global or cross-cutting across many components, like the current theme, authenticated user, or preferred language, and is React's own, dependency-free alternative to a separate state-management library like Redux for many simpler global-state needs.
1Understanding Context API
Context is created with createContext(defaultValue), which returns an object with a Provider component used to supply an actual value further down the tree, and any descendant component can read that value with the useContext hook, regardless of how deeply nested it is. It's specifically designed for data that's genuinely global or cross-cutting across many components, like the current theme, authenticated user, or preferred language, and is React's own, dependency-free alternative to a separate state-management library like Redux for many simpler global-state needs.
Context is React's own built-in tool for avoiding prop drilling — for many applications, especially without deeply complex, frequently-updating global state, it's a perfectly sufficient alternative to bringing in Redux or another external state library.
import { createContext, useContext } from 'react';
const LanguageContext = createContext('en');
function Greeting() {
const lang = useContext(LanguageContext);
return <p>{lang === 'es' ? 'Hola' : 'Hello'}</p>;
}2Practical Example
Here is a real-world application of Context API showing how it is used in production React code.
function App() {
return (
<LanguageContext.Provider value="es">
<Greeting />
</LanguageContext.Provider>
);
}3Best Practices
Follow these guidelines when working with Context API:
1. Use Context for genuinely global, cross-cutting values, like theme or authenticated user, rather than as a blanket replacement for regular parent-to-child props
2. Provide a sensible default value in createContext(), so components consuming the context still behave reasonably if rendered outside of an explicit Provider
3. Consider a dedicated state-management library like Redux instead of Context for very frequently-updating, complex global state, since Context re-renders every consumer on any value change
Tip: Context is React's own built-in tool for avoiding prop drilling — for many applications, especially without deeply complex, frequently-updating global state, it's a perfectly sufficient alternative to bringing in Redux or another external state library.
import { createContext, useContext } from 'react';
const LanguageContext = createContext('en');
function Greeting() {
const lang = useContext(LanguageContext);
return <p>{lang === 'es' ? 'Hola' : 'Hello'}</p>;
}