Introduction
The useContext hook in React is a powerful tool for simplifying context consumption in functional components. It provides a straightforward way to access context values without the need for a consumer component, streamlining code and improving readability. With useContext, you can manage global state, handle user authentication, implement theme switching, and facilitate localization effortlessly within your application.
This article explores the versatility of useContext through practical examples, demonstrating its usefulness in various real-world scenarios for efficient React development.
Here are some use cases of useContext with code examples:
Theme Switching
You can use context to manage the theme of your application and allow components to access the current theme.
import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
const ThemeProvider = ({ children }) => {
return (
<ThemeContext.Provider value="dark">
{children}
</ThemeContext.Provider>
);
};
const ThemeButton = () => {
const theme = useContext(ThemeContext);
return <button style={{ backgroundColor: theme === 'dark' ? 'black' : 'white', color: theme === 'dark' ? 'white' : 'black' }}>Toggle Theme</button>;
};
User Authentication
You can manage user authentication status using context and allow components to access the current user's information.
import React, { useContext } from 'react';
const AuthContext = React.createContext();
const AuthProvider = ({ children }) => {
const [user, setUser] = React.useState(null);
const login = (userData) => setUser(userData);
const logout = () => setUser(null);
return (
<AuthContext.Provider value={{ user, login, logout }}>
{children}
</AuthContext.Provider>
);
};
const UserInfo = () => {
const { user } = useContext(AuthContext);
return user ? <p>Welcome, {user.name}</p> : <p>Please log in</p>;
};
Localization
You can use context to manage the current locale of your application and allow components to access localized strings.
import React, { useContext } from 'react';
const LocaleContext = React.createContext('en');
const LocaleProvider = ({ children }) => {
const [locale, setLocale] = React.useState('en');
const changeLocale = (newLocale) => setLocale(newLocale);
return (
<LocaleContext.Provider value={{ locale, changeLocale }}>
{children}
</LocaleContext.Provider>
);
};
const LocalizedText = ({ id }) => {
const locale = useContext(LocaleContext);
// Fetch the localized string based on the locale and id
return <p>{localizedString}</p>;
};
These are just a few examples of how you can use useContext in React to manage and consume context values in various scenarios within your application. It simplifies the process of accessing context in functional components and promotes cleaner, more readable code