React Context Api ⚛️
I frequently utilize the React Context API in my side projects, and I’ve encountered the need to revisit previous projects to adapt their context implementations for new ones I’m working on. To streamline this process, I’ve created this snippet, making it effortless for me to duplicate and adapt it for new projects.
import React, { createContext, useContext, useState } from "react";
// Define the context type
interface AppContextType {
// Your data type
example: string
updateContextExample:(newValue:string)=>void;
}
// Create the context
const AppContext = createContext<AppContextType>(
{} as AppContextType
);
// Create the provider component
function AppProvider({ children }: { children: React.ReactNode }) {
const [example, setExample] = useState<string>("");
const updateContextExample = (newValue: string) => {
setExample(newValue);
};
return (
<AppContext.Provider value={{ example, updateContextExample }}>
{children}
</AppContext.Provider>
);
}
// Custom hook to use the context
const useAppContext = () => {
const context = useContext(AppContext);
if (!context) {
throw new Error("useAppContext must be used within an AppProvider.");
}
return context;
};
export { AppProvider, useAppContext };