Skip to content

Instantly share code, notes, and snippets.

@JLarky
Created August 1, 2022 17:29
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JLarky/a46055f673a2cb021db1a34449e3be07 to your computer and use it in GitHub Desktop.
Save JLarky/a46055f673a2cb021db1a34449e3be07 to your computer and use it in GitHub Desktop.
Ultimate example of solidjs context hook with nice type-safe (TypeScript) wrappers and reduced boilerplate by using `ReturnType`
import { createContext, createSignal, useContext, ParentComponent } from "solid-js";
function useProviderValue() {
const [isDark, setIsDark] = createSignal(false);
return { isDark, setIsDark };
}
export type ContextType = ReturnType<typeof useProviderValue>;
const DarkContext = createContext<ContextType | undefined>(undefined);
export const DarkProvider: ParentComponent = (props) => {
const value = useProviderValue();
return <DarkContext.Provider value={value}>{props.children}</DarkContext.Provider>
};
// bit.ly/SafeContext
export function useDark() {
const context = useContext(DarkContext);
if (context === undefined) {
throw new Error(`useDark must be used within a DarkProvider`);
}
return context;
}
export function useIsDark() {
return useDark().isDark;
}
export function useSetDark() {
return useDark().setIsDark;
}
@LexRiver
Copy link

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment