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.
If you enjoy my content and would like to support my work, you can buy me a coffee. Your support is greatly appreciated!
Disclaimer: This content has been generated by AI.