Understanding useContext
in React
The useContext
hook is a part of React's Hooks API that allows you to access the context value without wrapping your component in a Context.Consumer
. This hook provides a simpler and more concise way to access context, making your components cleaner and more readable.
Why Use useContext
?
Context is used to share data between components without having to pass props down manually at every level. Some common use cases for context include theming, user authentication, and managing global state.
How to Use useContext
Here's a step-by-step guide on how to use the useContext
hook:
1. Create a Context
const MyContext = React.createContext(defaultValue);
The createContext
function is used to create a context object. You can optionally provide a default value.
2. Provide the Context
<MyContext.Provider value={/* some value */}>
<YourComponent />
</MyContext.Provider>
Wrap your component tree with the Provider
component of the context you created. The value
prop of the provider will be available to any component wrapped by this provider.
3. Consume the Context
import React, { useContext } from 'react';
const YourComponent = () => {
const contextValue = useContext(MyContext);
return (
<div>{contextValue}</div>
);
};
Use the useContext
hook to access the context value directly within your functional component.
Example
Here's a complete example that demonstrates how to use the useContext
hook:
import React, { useContext, useState, createContext } from "react";
const StateContext = createContext(
{
currentUser: {},
userToken: null,
setCurrentUser: () => {},
setUserToken: () => {},
}
);
export const ContextProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState({
name: 'Tom Cook',
email: 'tomCook@email.com',
imageUrl: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80',
});
const [userToken, setUserToken] = useState('123');
return (
<StateContext.Provider value={{ currentUser, setCurrentUser, userToken, setUserToken }}>
{children}
</StateContext.Provider>
);
};
export const useStateContext = () => useContext(StateContext);
const App = () => (
<ContextProvider>
<RouterProvider router={router} />
</ContextProvider>
);
const UserProfile = () => {
const { currentUser } = useStateContext();
return (
<div>
<h1>User Profile</h1>
<img src={currentUser.imageUrl} alt={currentUser.name} />
<p>Name: {currentUser.name}</p>
<p>Email: {currentUser.email}</p>
</div>
);
};
export default App;
In this example, we create a StateContext
to manage the state of the current user and user token. The ContextProvider
component provides these values and functions to all child components. The UserProfile
component consumes the context value and displays the user's profile information.
Conclusion
The useContext
hook is a powerful tool that simplifies the process of consuming context in React. By using this hook, you can make your components cleaner and more maintainable.
Post a Comment
0Comments