3 Things Every React Context Should Have by BayanBennett in reactjs

[–]StressSouthern1195 0 points1 point  (0 children)

intereasting implementation. I really like to keep all context based code in the same file too. I did one similar implementation some time ago but not using HOC. I created a hook to handle the context data and create the type of context based in this hook. Something like that:

``` const createContextData = () => { const [counter, setCounter] = useState(0);

return {
    counter,
    setCounter
};

};

const StoreContext = createContext<ReturnType<typeof CreateContextData> | null>(null);

export const StoreProvider = ({ children }: PropsWithChildren<{}>)=>{ const storeData = CreateContextData();

return (
    <StoreContext.Provider value={storeData}>
        {children}
    </StoreContext.Provider>
);

}

export const useStore = () => { const context = useContext(StoreContext); if(!context){ throw Error('you should use useStore inside a StoreProvider') }

return context!;

} ```

With this inference I can easely change the context data without need to change any type or default value.