Mastering React Hooks: A Beginner's Guide to useContext
SRINIVAS K
Serving NP | Software Engineer specializing in React, TypeScript, JavaScript and Next.js | Building Scalable Web Applications with a Focus on Performance
?? Promo:
Since we discussed how to manage multiple pieces of state in one place with useReducer, now we’ll see how useContext allows you to share and access state across components without prop drilling.
If you've ever struggled with prop drilling—passing props through multiple layers of components useContext is here to simplify state sharing across the component tree. Whether you’re managing themes, user data, or other global states, useContext allows for efficient access to shared data without the hassle of repetitive prop passing.
?? What is useContext?
useContext is a React hook that enables a component to access values provided by a Context in any component within the provider’s tree, avoiding the need to pass props down manually. This can make state and data sharing across components easy and clean.
?? How Does It Work?
? Example:
Here's a basic example of using useContext to manage and share a theme:
import React, { useContext, createContext, useState } from 'react';
// Step 1: Create Context
const ThemeContext = createContext();
function App() {
const [theme, setTheme] = useState('light');
return (
// Step 2: Provide Context
<ThemeContext.Provider value={{ theme, setTheme }}>
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
return (
<div>
<ThemedButton /> // ? theme, setTheme not passed as Props
</div>
);
}
function ThemedButton() {
// ? Step 3: Consume Context
const { theme, setTheme } = useContext(ThemeContext);
return (
<button
onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}
style={{ background: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff' }}
>
Switch Theme
</button>
);
}
领英推荐
?? Key Points to Remember
const { theme } = useContext(ThemeContext); // Correct ?
// Avoid passing props unnecessarily
const theme = ThemeContext.theme; // ? This doesn’t use `useContext` properly
const providerValue = useMemo(() => ({ theme, setTheme }), [theme]); // Correct ?
const ThemeContext = createContext();
function ThemeProvider({ children }) {
const [state, dispatch] = useReducer(themeReducer, initialState);
return <ThemeContext.Provider value={{ state, dispatch }}>{children}</ThemeContext.Provider>;
}
?? Conclusion
useContext is a valuable tool for managing global state or data that many components need to access. By enabling components to "consume" values directly from a provider, it simplifies state management and reduces the need for prop drilling. But remember: use it strategically for the best performance.
?? What Next ?
Now that we know how to share global state, what if we need to memorize expensive calculations to improve our component’s performance? Can you guess the hook....?
Stay tuned to find out!