Day 3 of Mastering React Hooks – useContext
Kshitish Kumar Pothal
Next Js || React js || Frontend Developer || Wix || DSA || 500+ DSA Problem Solved || Java || Python || Kotlin || AWS
Introduction
Day 3 of my React Hooks journey takes me to the powerful useContext hook! This hook eliminates the pain of "prop drilling" by making it easier to share data across components, no matter how deeply nested they are in the component tree.
What is useContext?
The useContext hook is a way to access and consume context values in functional components. Context provides a way to share global data (like themes, user info, or language settings) without passing props manually through every level of your component tree.
How It Works
Using useContext is simple:
const MyContext = React.createContext(defaultValue);
<MyContext.Provider value={sharedData}>
<App />
</MyContext.Provider>
领英推荐
const value = useContext(MyContext);
Example: Theme Switcher
Here’s a simple example of how useContext works in practice:
// Create a context
const ThemeContext = React.createContext('light');
function App() {
const [theme, setTheme] = React.useState('light');
return (
<ThemeContext.Provider value={theme}>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle Theme
</button>
<Child />
</ThemeContext.Provider>
);
}
function Child() {
const theme = useContext(ThemeContext);
return <div>Current Theme: {theme}</div>;
}
Benefits of useContext
Things to Watch Out For
const memoizedValue = React.useMemo(() => ({ state, setState }), [state]);
Takeaway
useContext is your go-to hook for creating shared global data in React. Whether it’s a theme toggle, user preferences, or language settings, it simplifies how you manage and consume shared data.
Excited to explore the next hook tomorrow—stay tuned! ??