Context is a powerful feature in React that allows for state management and data sharing across components without the need to pass props down through every level of the component tree. It is particularly useful in scenarios where certain data needs to be accessible by many components at different nesting levels. Below are some common use cases for context, along with practical examples and best practices.
One of the most common use cases for context is to manage themes in an application. By using context, you can provide a theme object that can be accessed by any component in the tree, allowing for consistent styling across the application.
const ThemeContext = React.createContext();
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = React.useState('light');
const toggleTheme = () => {
setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));
};
return (
{children}
);
};
const ThemedComponent = () => {
const { theme, toggleTheme } = React.useContext(ThemeContext);
return (
);
};
Context can also be utilized for managing user authentication state. This allows you to provide user information and authentication status throughout your application without prop drilling.
const AuthContext = React.createContext();
const AuthProvider = ({ children }) => {
const [user, setUser] = React.useState(null);
const login = (userData) => {
setUser(userData);
};
const logout = () => {
setUser(null);
};
return (
{children}
);
};
const UserProfile = () => {
const { user } = React.useContext(AuthContext);
return {user ? `Welcome, ${user.name}` : 'Please log in'};
};
Another common use case is for language localization. By using context, you can easily manage and switch between different languages in your application.
const LanguageContext = React.createContext();
const LanguageProvider = ({ children }) => {
const [language, setLanguage] = React.useState('en');
const changeLanguage = (lang) => {
setLanguage(lang);
};
return (
{children}
);
};
const Greeting = () => {
const { language } = React.useContext(LanguageContext);
const greetings = {
en: 'Hello',
es: 'Hola',
fr: 'Bonjour',
};
return {greetings[language]};
};