REACT
React Context API: Syntax, Usage, and Examples
The React Context API provides a way to share state across components without passing props manually at every level. It simplifies state management, especially for global data like themes, authentication, or user preferences.
How to Use React Context API
The Context API consists of three main parts: createContext
, Provider
, and useContext
. You first create a context, wrap components with a Provider
, and then access the context inside any component using useContext
.
Basic Syntax of React Context API
import { createContext, useState, useContext } from "react";
// Create a Context
const ThemeContext = createContext();
// Create a Provider Component
function ThemeProvider({ children }) {
const [theme, setTheme] = useState("light");
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
// Custom Hook to use the context
function useTheme() {
return useContext(ThemeContext);
}
Here, ThemeContext
holds the global state, and ThemeProvider
wraps the application to provide the context to all child components. The useTheme
custom hook simplifies access to the context.
When to Use React Context API
The Context API is useful when multiple components need access to the same state.
Managing Theme (Dark Mode)
A global theme setting allows users to toggle between light and dark modes without passing props manually.
function ThemeToggle() {
const { theme, setTheme } = useTheme();
return (
<button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
Switch to {theme === "light" ? "Dark" : "Light"} Mode
</button>
);
}
Handling User Authentication
Context helps store authentication data and makes it available across components.
const AuthContext = createContext();
function AuthProvider({ children }) {
const [user, setUser] = useState(null);
return (
<AuthContext.Provider value={{ user, setUser }}>
{children}
</AuthContext.Provider>
);
}
function useAuth() {
return useContext(AuthContext);
}
Managing Language Preferences
A language preference stored in context lets users switch between different languages dynamically.
const LanguageContext = createContext();
function LanguageProvider({ children }) {
const [language, setLanguage] = useState("en");
return (
<LanguageContext.Provider value={{ language, setLanguage }}>
{children}
</LanguageContext.Provider>
);
}
function useLanguage() {
return useContext(LanguageContext);
}
Examples of React Context API
Using Context in a Component
Once a context is created and provided, any child component can access it using useContext
.
function DisplayTheme() {
const { theme } = useTheme();
return <p>Current Theme: {theme}</p>;
}
React Context API Example with Multiple Contexts
You can combine multiple contexts by nesting Provider
components.
function App() {
return (
<AuthProvider>
<ThemeProvider>
<LanguageProvider>
<MainComponent />
</LanguageProvider>
</ThemeProvider>
</AuthProvider>
);
}
Updating Context State
A context value can be updated dynamically inside components.
function LoginButton() {
const { setUser } = useAuth();
return (
<button onClick={() => setUser({ name: "Alice" })}>Login as Alice</button>
);
}
Learn More About React Context API
Context API vs. Redux in React
While both Context API and Redux manage state, they serve different purposes.
Context API is best suited for small to medium-sized applications where state doesn't change frequently or require complex interactions. It's built into React, making it easy to use with minimal setup. However, when multiple components re-render due to state changes, performance can become an issue.
Redux, on the other hand, is more structured and suitable for larger applications with complex state logic. It provides features like reducers, middleware, and dev tools that make debugging easier. Unlike Context API, Redux ensures better performance by using a centralized store and optimizing updates through selectors.
If you're working on a small app where state needs to be shared across multiple components, Context API is a simple and effective choice. But for large-scale applications with deeply nested components and frequent state updates, Redux is often the better option.
Optimizing Performance with Context API
Using Context API with large applications can lead to unnecessary re-renders. To optimize performance, you can:
- Use multiple smaller contexts instead of a single large one.
- Wrap the context value inside
useMemo
to prevent unnecessary updates. - Use context selectively instead of wrapping the entire application.
const MemoizedThemeProvider = ({ children }) => {
const [theme, setTheme] = useState("light");
const value = useMemo(() => ({ theme, setTheme }), [theme]);
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
};
Context API with Class Components
Before React hooks, Context.Consumer
was used in class components to access context.
class ThemeButton extends React.Component {
static contextType = ThemeContext;
render() {
return <button>{this.context.theme}</button>;
}
}
However, with Hooks, useContext
is the preferred way to use Context API in functional components.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.