DEV Community

Gloria Lim
Gloria Lim

Posted on • Edited on

Custom Code Snippets in VS Code

When coding in Visual Studio Code, how often did you feel unsure about the syntax or format of a function, and had to look it up in Google? Were you so focused coding in Python for the past 3 months and have now forgotten how React hooks look like?

This is a great reason to set up custom snippets in VS Code.

Recently, I added custom snippets for React hooks. The snippet lives in a JSON file and looks like this:

"useReducer Hook": {
            "prefix": "use",
            "body": ["const ${1:INITIAL_STATE} = {", "", "}", "", "function reducer(state, action) {", "  switch (action.type) {", "    case \"${4:NameMe}\":", "      // Do something here", "      return", "  }", "}", "", "const [${2:state}, ${3:dispatch}] = useReducer(reducer, $1)"],
            "description": "Creates a useReducer expression"
    }
Enter fullscreen mode Exit fullscreen mode
  • The key for the snippet object, "useReducer Hook" is the snippet name.
  • prefix defines one or more trigger words that display the snippet in IntelliSense.
  • body is one or more lines of content, which will be joined as multiple lines upon insertion. Newlines and embedded tabs will be formatted according to the context in which the snippet is inserted.
  • description is an optional description of the snippet displayed by IntelliSense.

Source: VS Code Docs

In my React JavaScript file, I can simply type in 'use' as I had predefined it as a shortcut to the custom snippet.

Code snippet preview

💡What It Looks Like

As you can see, I have 3 predefined custom snippets there. It shows a preview of the code snippet, and when I hit enter, it prints the snippet to my file.

Code snippet

If you look closely at the configuration, you will notice the parameters that starts with $. These are the user insertion points, and it will automatically place your text cursor there right after the snippet is added to your file.

🔧To Create A Custom Snippet

(for just about anything!)

  1. In VS Code, open File > Preferences > Configure User Snippets.
  2. You have the option to create a New Global Snippets file option to create a global configuration file. Or New Snippets file for ... to create a local configuration file.
  3. Select the language for the code snippet.
  4. Give the file an easily identifiable name.
  5. Notice the comments in the newly created file. It gives you a guide on what is required for the custom snippet to work.

Note: You can copy and paste the example in the commented out code there as a baseline.

I have also created XML and SQL code snippets for my daily work and it has been a great experience!

You can visit this Gist to see an example of my JavaScript configuration code.

💫Shortcut

You can also use this wonderful snippet generator by Pawel Grzybek to create your snippets.

If you gave this a try, let me know your thoughts!

Top comments (0)