React's context API allows you to share data between components without having to pass props down through every level of the component tree. The useContext
hook is used to access the value of a context object in a functional component.
Creating a Context
Before we can use useContext
, we need to create a context object. We can do this with the createContext
function from the React library in UserContext.js
. Here's an example:
import { createContext } from 'react';
const UserContext = createContext();
export default UserContext;
In this example, we create a new context object called UserContext
.
Providing a Context Value
To provide a value to a context, we wrap the relevant components with a Provider
component. Here's an example:
import { useState } from 'react';
import UserContext from './UserContext';
import Header from './Header';
function Layout() {
const [user, setUser] = useState({ name: 'John Doe', email: 'johndoe@example.com' });
return (
<UserContext.Provider value={user}>
<Header />
<Main />
<Footer />
</UserContext.Provider>
);
}
export default Layout;
In this example, we provide a user
object as the value of the UserContext
by wrapping the relevant components with a UserContext.Provider
component.
Consuming a Context Value
To consume a context value, we use the useContext
hook in a functional component. Here's an example:
import { useContext } from 'react';
import UserContext from './UserContext';
function Header() {
const user = useContext(UserContext);
return (
<header>
<h1>{user.name}'s App</h1>
<p>{user.email}</p>
</header>
);
}
export default Header;
In this example, we use useContext
to access the value of the UserContext
and use it to render the user's name and email in the header of our app.
Conclusion
The useContext
hook allows us to access the value of a context object in a functional component. By creating a context and providing a value with a Provider
component, we can share data between components without having to pass props down through every level of the component tree. In the next article in this series, we'll cover the useRef
hook, which is used for creating mutable references to elements or values.