Skip to content

Instantly share code, notes, and snippets.

@bel0v
Last active July 25, 2022 07:26
Show Gist options
  • Save bel0v/ad9f047bbfe7711d966a64f5f77cab07 to your computer and use it in GitHub Desktop.
Save bel0v/ad9f047bbfe7711d966a64f5f77cab07 to your computer and use it in GitHub Desktop.
VsCode snippets
{
"context-hook": {
"prefix": "context",
"body": [
"import React, {useState, createContext, useContext} from 'react'",
"",
"interface ${1/(.*)/${1:/capitalize}/}ContextAPI {",
" $1: number",
" set${1/(.*)/${1:/capitalize}/}: (data: number) => void",
"}",
"type ${1/(.*)/${1:/capitalize}/}ProviderProps = {children: React.ReactNode}",
"",
"const ${1/(.*)/${1:/capitalize}/}Context = createContext<${1/(.*)/${1:/capitalize}/}ContextAPI|undefined>(undefined)",
"",
"export const ${1/(.*)/${1:/capitalize}/}Provider = ({children}: ${1/(.*)/${1:/capitalize}/}ProviderProps) => {",
" const [$1, set${1/(.*)/${1:/capitalize}/}] = useState(0)",
" const value = {$1, set${1/(.*)/${1:/capitalize}/}}",
" return <${1/(.*)/${1:/capitalize}/}Context.Provider value={value}>{children}</${1/(.*)/${1:/capitalize}/}Context.Provider>",
"}",
"",
"export function use${1/(.*)/${1:/capitalize}/}() {",
" const context = useContext(${1/(.*)/${1:/capitalize}/}Context)",
" if (context === undefined) {",
" throw new Error('use${1/(.*)/${1:/capitalize}/} must be used within a ${1/(.*)/${1:/capitalize}/}Provider')",
" }",
" return context",
"}",
""
],
"description": "Creates React context hook blueprint"
}
}
@bel0v
Copy link
Author

bel0v commented Feb 16, 2022

gist.mp4

@bel0v
Copy link
Author

bel0v commented Feb 16, 2022

installation: Cmd+shift+P -> "Preferences: configure user snippets" -> "New global snippets file"

@bel0v
Copy link
Author

bel0v commented Jul 25, 2022

Updated gist: createContext with initial undefined value. Otherwise context === undefined check doesn't make sense.

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