The useContext
hook in React is used to access the values stored in a context. Context provides a way to share values between components without having to explicitly pass props through every level of the component tree. This can be especially useful for things like theming, user authentication, or global state management.
useContext
Here’s a step-by-step guide to using the useContext
hook:
createContext
function to create a context.Provider
component to pass the context value down the component tree.useContext
hook to access the context value in any component.Create a context in a separate file (e.g., ThemeContext.js
):
import React, { createContext } from 'react'; const ThemeContext = createContext(); export default ThemeContext;
Wrap the part of your component tree where you want to provide the context value with the Provider
component. This is usually done in a higher-level component, like App.js
:
import React, { useState } from 'react'; import ThemeContext from './ThemeContext'; import ChildComponent from './ChildComponent'; const App = () => { const [theme, setTheme] = useState('light'); const toggleTheme = () => { setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light')); }; return (); }; export default App;
useContext
Here's another example demonstrating how to use useContext
for user authentication:
import React, { createContext, useState } from 'react'; const UserContext = createContext(); export const UserProvider = ({ children }) => { const [user, setUser] = useState(null); const login = (userData) => { setUser(userData); }; const logout = () => { setUser(null); }; return ({children} ); }; export default UserContext;
Wrap your application or specific parts of your application with the UserProvider
:
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import { UserProvider } from './UserContext'; ReactDOM.render(, document.getElementById('root') );