
ReactJS useContext Example
ReactJS useContext Example: The useContext hook in React is used to access the value of a Context in functional components. It simplifies the process of sharing data between components without having to pass props down manually through every level of the component tree, a process commonly referred to as "prop drilling."
Key Concepts
Context API: React’s Context API allows you to create a global data store that components can access without directly passing props.
useContext: The useContext hook is a way for functional components to access the values stored in a Context without the need for Consumer component
ReactJS useContext Example: How useContext Works
Here’s an example of using useContext to toggle between light and dark themes:
Create a Context: Use React.createContext() to create a Context. This serves as a container for the data you want to share.
import React, { useContext, useState } from "react";
const ThemeContext = React.createContext();
Create a Provider Component: Provide the Context Value:
Use the Provider component of the Context to wrap the part of your component tree where the data should be accessible. Pass the data through the value prop of the Provider.
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState("light");
const toggleTheme = () => {
setTheme((prevTheme) => (prevTheme === "light" ? "dark" : "light"));
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
};
Consume the Context with useContext:
Use the useContext hook to access the data in any child component.
const ThemeSwitcher = () => {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
<div style={{ background: theme === "light" ? "#fff" : "#333", color: theme === "light" ? "#000" : "#fff" }}>
<p>Current Theme: {theme}</p>
<button onClick={toggleTheme}>Toggle Theme</button>
</div>
);
};
Use the Provider in the App
const App = () => {
return (
<ThemeProvider>
<ThemeSwitcher />
</ThemeProvider>
);
};
export default App;
Benefits of useContext
Eliminates Prop Drilling: Passes data directly to components that need it, avoiding the need to pass props through intermediate components.
Improves Readability: Makes the code cleaner and easier to manage, especially in large applications.
Reusability: Allows creating reusable Contexts for features like themes, authentication, or user preferences.
Comments