Code snippets for the rescue
You know those repetitive tasks that you take a look and think about: it could be great to never write this again (or memorize).
Code snippets could be so powerful, you should learn this asap!
A code snippet is a block of predefined text that you can customize with some inputs.
Creating a global code snippet
Today i will show you one of my new favorites code snippets: react context with typescript.
If you have to write some of those anytime, you know that could be a little bit confusing(to say the least).
First of all, let’s see a basic react context setup to understand the power of this code snippet:
Alright, now that we know how to write a basic(not so basic) react context with typescript, it could be nice to have an code snippet and never write all these lines again. Let’s do this!
To create a global code snippet, open VS Code and follow these steps:
- press ctrl+shift+p
- type: snippet
- select “Configure code snippet”
- select “new global snippets file”
Now you have a new global code snippet file! Cool!
A code snippet file is just a json with some informations about the snippet, like its name, the shortcut to use it and the body.
Here’s the react context code snippet, just paste it in the new file and save:
{
"create react context": {
"scope": "typescriptreact",
"prefix": "tscontext",
"body": [
"import { createContext, useContext, PropsWithChildren } from 'react';",
"",
"type $1Type = {}",
"",
"export const $1 = createContext({} as $1Type)",
"",
"export const $1Provider = ({ children }: PropsWithChildren) => {",
" return (",
" <$1.Provider value={{}}>",
" {children}",
" </$1.Provider>",
" );",
"}",
"",
"export const use$1 = () => useContext($1)"
],
"description": "create react context with hook"
}
}
To use it, create a .tsx file, type tscontext
than hit tab. Choose the context name (ie: BasicContext) and hit esc
.
And that’s it, the snippet will fill all variables/types/function names according to the name that you choose.
Snippet scope
On VS Code, snippets could be global or scoped to the project. You could select the scope after selecting “Configure code snippet” step.
Extension
There’s an amazing VS Code extension with a bunch of code snippets for React. Take a look, it is really great!
Thank you for the attention, bye.
Top comments (3)
Snippet Generator is a really handy web app that helps you convert code to snippet format.
wow! Thank you for sharing
very nice 😉