The useContext
hook is a powerful hook in React that allows you to access the value of a context directly in a functional component, bypassing the need to pass props down through every level of the component tree. Context provides a way to share values like authentication status, theme settings, language preferences, and other global data across components without having to pass props manually at every level.
1. What is the useContext
Hook?
The useContext
hook allows you to subscribe to React context and access its value. Context is a way to share values across different components without explicitly passing props through every level of the tree.
2. Creating Context
Before you can use the useContext
hook, you need to create a context using React.createContext()
. This creates a context object that can be used to provide and consume values.
import React, { createContext, useState, useContext } from 'react';
// Creating the context
const ThemeContext = createContext();
Here, ThemeContext
is a context object that can hold a value (e.g., theme settings like light or dark mode).
3. Providing Context Value
Once the context is created, you need to provide a value using the Provider
component. The Provider
component allows you to pass the context value to the component tree.
function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<Header />
<Main />
</ThemeContext.Provider>
);
}
Here, the ThemeContext.Provider
provides the current theme
and setTheme
function to all components that are inside its tree.
4. Consuming Context with useContext
Now that the context is provided, any component inside the provider can access the context value using the useContext
hook.
function Header() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<div>
<h1>Current Theme: {theme}</h1>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle Theme
</button>
</div>
);
}
In this example, the Header
component uses useContext(ThemeContext)
to access the theme
and setTheme
values, allowing it to display and update the current theme.
5. How useContext
Works
- Context Provider: It’s the component that supplies a value to be shared.
- Context Consumer (useContext hook): It’s the function used by a component to access the shared value.
When the context value changes, all the components that are consuming the context will automatically re-render.
6. Example: Theme Context with useContext
Here’s a complete example of how to use useContext
to manage theme (light/dark mode) across a React app.
import React, { createContext, useState, useContext } from 'react';
// Create the context
const ThemeContext = createContext();
function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<Header />
<Main />
</ThemeContext.Provider>
);
}
function Header() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<header style={{ backgroundColor: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff' }}>
<h1>Header</h1>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle Theme
</button>
</header>
);
}
function Main() {
const { theme } = useContext(ThemeContext);
return (
<main style={{ backgroundColor: theme === 'light' ? '#f4f4f4' : '#222', color: theme === 'light' ? '#000' : '#fff' }}>
<h2>Main Content</h2>
</main>
);
}
export default App;
In this example:
- The
App
component provides thetheme
andsetTheme
using theThemeContext.Provider
. - The
Header
andMain
components consume thetheme
value using theuseContext
hook and update their styles accordingly. - The
setTheme
function toggles between ‘light’ and ‘dark’ modes.
7. Multiple Contexts
You can use multiple contexts in a component by calling useContext
multiple times with different context objects.
const UserContext = createContext();
const LanguageContext = createContext();
function UserProfile() {
const user = useContext(UserContext);
const language = useContext(LanguageContext);
return (
<div>
<h1>{user.name}</h1>
<p>Preferred Language: {language}</p>
</div>
);
}
8. Best Practices for useContext
- Keep Context Values Simple: Context should store data that is needed globally. Avoid putting large or complex objects in context. Instead, store values that multiple components need.
- Avoid Excessive Re-renders: When the context value changes, all components that consume it will re-render. To avoid unnecessary re-renders, consider optimizing state updates or using multiple contexts.
- Context for Global Data: Context is best used for global data like authentication status, themes, and user preferences. Don’t use it for every piece of state in your application.