Simplify Context Usage with a Custom Hook
When using the Context API in multiple components, you can streamline access by creating a custom hook for your context. This tiny hack reduces boilerplate and makes accessing context data more concise
Instead of using useContext directly every time, create a custom hook:
1. Define the Context and Provider:
import React, { createContext, useContext, useState } from 'react';
const ThemeContext = createContext();
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState("light");
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
2. Create a Custom Hook:
export function useTheme() {
return useContext(ThemeContext);
}
3. Use the Custom Hook in Components:
function ThemedComponent() {
const { theme, setTheme } = useTheme();
return (
<div style={{ background: theme === "light" ? "#fff" : "#333", color: theme === "light" ? "#000" : "#fff" }}>
<p>Current Theme: {theme}</p>
<button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
Toggle Theme
</button>
</div>
);
}
You Might Also Like
Custom Hook : Simplify Code with Reusable Logic
Setting up a reusable data-fetching function to simplify API calls and state management. # State In...
Destructuring Props in Functional Components
When you pass any props to any componenet, as in this example passing name and age as props to Profi...