How Pros Automate Repetitive Code using VS Code
Tags: vscode, productivity, programming, json
Published: 2021-09-05 04:02:44

While **Programming**, you are bound to encounter _Repetitive Code_, writing which is a complete **waste of time**. I am not talking about **Non-DRY Code**, but _Essentials Code_ that is necessary to be written. An example of this would be connecting **State**/**Dispatch** to **Props** using **React-Redux**.

Anyone who has worked on a decent-sized **React-Redux** project knows how many times you have to write the same code to connect the **Redux Store Data** to the **Component Props**.

Today we are going to fix that and provide you with a way to _streamline **ANY** Repetitive Code_ you have and **Maximize your Productivity**.

# What are **Snippets** in **VS Code**?

**VS Code** is an Amazing Code Editor that provides a _plethora of tools_ to take your **productivity** to the **next level**. **Snippets** are just one such tool.

**Snippets** can be thought of as **Templates** that enable you _write code once_ and reuse it, _as per requirement_. It allows **Variables** as well as **Dynamic User Inputs**.

If you have been using **VS Code** for some time, you are bound to come across **Snippets**. 

![Snippet](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0dl9v0jabeyz1e5zp616.png)

Some **Snippets** come pre-built with **VS Code**. You can install some extensions to add event more **Snippets**, but most importantly, you can create your own **Snippets** to cater to your very own needs.

# Creating our first **Snippets**

Creating a **Snippets** is fairly simple:

1. Go to **File > Preferences > User Snippets** (possibly **Code > Preferences > User Snippets** on macOS).

    Or you might use `F1` to bring up the **Command Palette** and search for **User Snippets**

2. Select the type of **Snippet** you want to create (**language-specific**, **project-specific** or **global**)

    ![Snippet Creation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e23x82lrpzerzvzx2sxy.png)
3. Add the following in the created `.code-snippets` file

    ```json
    {
	"Signature": {
            "scope": "html",
            "prefix": "hello",
            "body": [
                "Hello!!!"
            ],
            "description": "Hello"
        }
    }
    ```
4. Done! Now when you type **"hello"** in an **HTML** file, you would be to use the **Snippet**

This wasn't a practical example, but we did manage to get our feet wet at making **Snippets**.

On inspecting the **Snippet** definition, we find the `scope` that declares which files the **Snippet** should be used in. The `prefix` mentions the **prefix text** that will trigger the **Snippet** to show up. The `body` defines the **body** of the **Snippet**(each line of the **Snippet** would be a new **string** in array). And finally, `description` is a short description of the **Snippet**'s function.

Let us make a couple of **practical ones** to _deepen our understanding_ and solve the issue mentioned in the _Intro of the article_ (connecting **State**/**Dispatch** to **Props** using **React-Redux**).

# Snippet 1: Leaving a Signature

Let's try making a snippet that leaves a _signature_ like this in any file and isn't restricted to only **Python**

```py
"""
Name: Tapajyoti Bose
Modified on: 05 September 2021 08:38:35
"""
```

We would also like the **Snippet** to update the **date** and **time** dynamically, of course.

Luckily, **VS Code** provides a bunch of **variables** for this purpose. 

We would be using `BLOCK_COMMENT_START` and `BLOCK_COMMENT_END` to automatically generate the block comments for any language and `CURRENT_DATE`, `CURRENT_MONTH_NAME`, `CURRENT_YEAR`, `CURRENT_HOUR`, `CURRENT_MINUTE`, & `CURRENT_SECOND` to generate the **date** and **time** dynamically.

**NOTE**: To get the complete list of **variables**, [click here](https://code.visualstudio.com/docs/editor/userdefinedsnippets#_variables)

So the **Snippet** would initially look like this:

```json
"Signature": {
    "scope": "python,javascript,typescript,html,css",
    "prefix": "signature",
    "body": [
        "$BLOCK_COMMENT_START",
        "Name: Tapajyoti Bose",
        "Modified on: $CURRENT_DATE $CURRENT_MONTH_NAME $CURRENT_YEAR $CURRENT_HOUR:$CURRENT_MINUTE:$CURRENT_SECOND",
        "$BLOCK_COMMENT_END"
    ],
    "description": "Leave a signature"
}
```

Now within **Python**, **Javascript**, **Typescript**, **HTML**, **CSS** files, you would be able to leave a signature.

![Signature](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b7yb23slsuogytjmkzp7.png)

You might be wondering if _extending the functionality_ to _all languages_ would require you to add the _names of all languages_. Luckily there is an easy solution: just remove the `scope` from the **Snippet** definition and **Viola!** the functionality is extended to all languages!

# Snippet 2: Connecting Redux to React Props

This is even easier than the **Signature Snippet**. Just copy the following code in the snippet definition, and you are done:

```json
"Connect Component to Redux": {
	"scope": "javascriptreact,typescriptreact",
	"prefix": "connect",
	"body": [
		"const mapStateToProps = (state) => ({",
		"\t$1",
		"})",
		"",
		"const mapDispatchToProps = (dispatch) => ({",
		"\t$0",
		"})",
		"",
		"export default connect(mapStateToProps, mapDispatchToProps)($TM_FILENAME_BASE)"
	],
	"description": "Connect React Component to Redux"
}
```

Let us examine what is being done.

We are scoping the **Snippet** to **React** based projects for obvious reasons.

In the body, you might be seeing `$0` and `$1` for the first time. These are placeholders for **tab-able** positions where the user should enter _their own logic_ (the parts of the **store** they want to connect to the **props** in this case).

We are using the **File Name** as the **Component Name**, as in _most_ cases, the convention is using the **Component Name** to be the same as the **File Name**.

# Wrapping Up

In this article, we went over how you can **Automate Repetitive Code** using **VS Code Snippets**. Now you can create **Custom Snippets** that solve your own problems and boost your productivity to new heights.

**Happy Developing!**

![Thumbs Up](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eqh8teicsquqqivxlfus.gif)

Finding **personal finance** too intimidating? Checkout my **Instagram** to become a [**Dollar Ninja**](https://www.instagram.com/the.dollar.ninja/)

# Thanks for reading

Want to work together? Contact me on [Upwork](https://www.upwork.com/o/profiles/users/~01c12e516ee1d35044/)

Want to see what I am working on? Check out my [GitHub](https://github.com/ruppysuppy)

I am a freelancer who will start off as a Digital Nomad in mid-2022. Want to catch the journey? Follow me on [Instagram](https://www.instagram.com/tapajyotib/)

Follow my blogs for weekly new tidbits on [Dev](https://dev.to/ruppysuppy)

**FAQ**

These are a few commonly asked questions I get. So, I hope this **FAQ** section solves your issues.

1. **I am a beginner, how should I learn Front-End Web Dev?**
    Look into the following articles:
    1. [Front End Development Roadmap](https://dev.to/ruppysuppy/front-end-developer-roadmap-zero-to-hero-4pkf)
    2. [Front End Project Ideas](https://dev.to/ruppysuppy/5-projects-to-master-front-end-development-57p)

2. **Would you mentor me?**
    Sorry, I am already under a lot of workload and would not have the time to mentor anyone.

3. **Would you like to collaborate on our site?**
    As mentioned in the _previous question_, I am in a time crunch, so I would have to pass on such opportunities.

**Connect to me on**

-   [LinkedIn](https://www.linkedin.com/in/tapajyoti-bose-429a601a0)
-   [Portfolio](https://tapajyoti-bose.vercel.app)
-   [Upwork](https://www.upwork.com/o/profiles/users/~01c12e516ee1d35044/)
-   [GitHub](https://github.com/ruppysuppy)
-   [Instagram](https://www.instagram.com/tapajyotib/)