useContext
The useContext hook in React is used to access the value of a context without wrapping a component in a Context.Consumer. It allows you to easily access data that's been provided by a Context.Provider higher up in the component tree. This is particularly useful for sharing global data like theme, user authentication, or language settings across multiple components.
Basic Syntax
The basic syntax of useContext is straightforward:
const value = useContext(MyContext);
Here, MyContext is the context object created by React.createContext().
How it Works
-
Create Context: First, you create a context using
React.createContext().const MyContext = React.createContext(); -
Provide Context: Use the
Context.Providerto wrap the component tree that needs access to the context value.<MyContext.Provider value={{ someValue: 'hello', anotherValue: 'world' }}>
{/* children components */}
</MyContext.Provider> -
Consume Context: Inside any child component, you can now use
useContextto access the context value.const { someValue, anotherValue } = useContext(MyContext);
Example
Here's a simple example to demonstrate how useContext works:
import React, { useContext } from 'react';
// 1. Create Context
const ThemeContext = React.createContext('light');
function App() {
return (
// 2. Provide Context
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
return (
<div>
<ThemedButton />
</div>
);
}
function ThemedButton() {
// 3. Consume Context
const theme = useContext(ThemeContext);
return <button className={`btn btn-${theme}`}>I am styled by theme context!</button>;
}
export default App;
In this example, the ThemedButton component uses the useContext hook to get the current theme ("dark") from the ThemeContext.Provider in the App component.
Caveats
-
useContextwill only return the current context value, or the default if the component is not wrapped in aContext.Provider. It does not provide a way to subscribe to context changes. -
Multiple
useContexthooks can be used in a single component to consume multiple contexts.
Summary
The useContext hook simplifies the process of accessing context values in functional components, making it easier to share state and behavior across your application. It eliminates the need to wrap each component in a Context.Consumer, making your component tree cleaner and more readable.