Skip to content

Instantly share code, notes, and snippets.

@daniellealexis
Last active September 5, 2021 02:51
Show Gist options
  • Save daniellealexis/7b01e4d8a2680e288b37cca63c6dfad1 to your computer and use it in GitHub Desktop.
Save daniellealexis/7b01e4d8a2680e288b37cca63c6dfad1 to your computer and use it in GitHub Desktop.
Generate Typescript React Provider
import React, { useContext, useState } from 'react';
type GeneratedExampleContextValue = {};
type GeneratedExampleContextType = [
GeneratedExampleContextValue,
React.Dispatch<React.SetStateAction<GeneratedExampleContextValue>>
];
const defaultProviderValue: GeneratedExampleContextValue = {};
const GeneratedExampleContext = React.createContext<GeneratedExampleContextType>([
defaultProviderValue,
() => {},
]);
export const useGeneratedExample = (): GeneratedExampleContextType =>
useContext(GeneratedExampleContext);
type GeneratedExampleProviderProps = {
children: React.ReactNode;
testValue?: GeneratedExampleContextValue;
};
const GeneratedExampleProvider = (props: GeneratedExampleProviderProps) => {
const contextValue = useState<GeneratedExampleContextValue>(props.testValue || defaultProviderValue);
return (
<GeneratedExampleContext.Provider value={contextValue}>
{props.children}
</GeneratedExampleContext.Provider>
);
};
export default GeneratedExampleProvider;
{
"Generate Provider": {
"prefix": "prov",
"body": [
"import React, { useContext, useState } from 'react';",
"",
"type ${1:${TM_FILENAME_BASE/(\\Provider)//g}}ContextValue = {};",
"",
"type ${1}ContextType = [",
" ${1}ContextValue,",
" React.Dispatch<React.SetStateAction<${1}ContextValue>>",
"];",
"",
"const defaultProviderValue: ${1}ContextValue = {};",
"",
"const ${1}Context = React.createContext<${1}ContextType>([",
" defaultProviderValue,",
" () => {},",
"]);",
"",
"export const use${1} = (): ${1}ContextType =>",
" useContext(${1}Context);",
"",
"type ${1}ProviderProps = {",
" children: React.ReactNode;",
" testValue?: ${1}ContextValue;",
"};",
"",
"const ${1}Provider = (props: ${1}ProviderProps) => {",
" const contextValue = useState<${1}ContextValue>(props.testValue || defaultProviderValue);",
"",
" return (",
" <${1}Context.Provider value={contextValue}>",
" {props.children}",
" </${1}Context.Provider>",
" );",
"};",
"",
"export default ${1}Provider;",
""
],
"description": "Generate Provider"
}
}
@daniellealexis
Copy link
Author

This works with a filename in the pattern of "${Whatever}Provider," but it isn't necessary. It will use the filename otherwise. It's just a pattern I like for my own code.

@daniellealexis
Copy link
Author

daniellealexis commented Sep 3, 2021

To use, add the code from typescriptreact.json, into your own typescriptreact.json snippets file. You could add it to your global snippets file if you'd like, but then you'll have to add a scope: "scope": "typescriptreact",

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