Creating a custom useContext
-like hook in vanilla JavaScript involves using closures and creating a simple context provider. Below is a basic example demonstrating how you might achieve this:
// CustomContext.js
function createContext(defaultValue) {
let contextValue = defaultValue;
const listeners = new Set();
function useContext() {
return contextValue;
}
function updateContext(newValue) {
if (contextValue !== newValue) {
contextValue = newValue;
listeners.forEach((listener) => listener());
}
}
function subscribe(listener) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
return { useContext, updateContext, subscribe };
}
// Usage
const ExampleContext = createContext('Hello from Context!');
// ExampleComponent.js
function ExampleComponent() {
const contextValue = ExampleContext.useContext();
// Subscribe to context updates
const unsubscribe = ExampleContext.subscribe(() => {
const updatedValue = ExampleContext.useContext();
console.log('Context updated:', updatedValue);
});
// Unsubscribe when the component is unmounted (optional)
// useEffect(() => {
// return () => unsubscribe();
// }, []);
return contextValue;
}
// ExampleProvider.js
function ExampleProvider({ children }) {
// Wrap your component tree with the provider
return children;
}
// Usage in the application
const appRoot = document.getElementById('app');
const App = () => {
return (
<ExampleProvider>
<ExampleComponent />
</ExampleProvider>
);
};
ReactDOM.render(<App />, appRoot);
This example demonstrates a basic context implementation using closures. The createContext
function creates a context object with useContext
, updateContext
, and subscribe
functions. Components can use these functions to access and update the context value.
Keep in mind that this is a simplified version, and real-world scenarios might involve additional considerations, such as handling multiple providers, context hierarchies, or optimizing updates. In a practical application, using a library like React for state management is often more convenient and efficient.
Support My Work ❤️
If you enjoy my content and find it valuable, consider supporting me by buying me a coffee. Your support helps me continue creating and sharing useful resources. Thank you!
Connect with Me 🌍
Let’s stay connected! You can follow me or reach out on these platforms:
🔹 YouTube – Tutorials, insights & tech content
🔹 LinkedIn – Professional updates & networking
🔹 GitHub – My open-source projects & contributions
🔹 Instagram – Behind-the-scenes & personal updates
🔹 X (formerly Twitter) – Quick thoughts & tech discussions
I’d love to hear from you—whether it’s feedback, collaboration ideas, or just a friendly hello!
Disclaimer
This content has been generated with the assistance of AI. While I strive for accuracy and quality, please verify critical information independently.
Top comments (0)