DEV Community

Cover image for Creating a Code Snippet in VS Code to Increase Productivity
Girish Sawant
Girish Sawant

Posted on

Creating a Code Snippet in VS Code to Increase Productivity

Hi all,

Today, I am sharing some coding practices that have increased my productivity and time efficiency through the use of code snippets. I always prefer using smart tools over conventional ones to improve my workflow further.

Background

Let's start with a scenario from a React dashboard project where I frequently used drawer components. Each drawer had similar functionality for submitting form data. As a React developer, I had two options:

  1. Create a reusable drawer component for multiple modules.
  2. Create cloned drawer components specific to different application modules.

In this case, I chose the second option. I avoided creating a reusable drawer component because I anticipated needing to pass different props and logic in various instances.

However, copying and pasting the drawer component, removing unnecessary states, logic, and UI parts, and refactoring component and variable names became time-consuming.

Solution: Custom Snippets

I discovered that creating user-defined snippets could streamline this process. Here’s the snippet I created for a drawer component with a form:

{
    "React Drawer with Form": {
        "prefix": "drawer-form",
        "body": [
            "import { FileText, X } from \"@phosphor-icons/react\";",
            "import { Button, Drawer, Form } from \"antd\";",
            "import KeyboardButton from \"components/Commons/KeyboardButtons\";",
            "import { useState } from \"react\";",
            "import { useEventListener } from \"usehooks-ts\";",
            "",
            "type T$1Drawer = {",
            "    open: boolean;",
            "    onClose: () => void;",
            "};",
            "",
            "type TFormValues = {};",
            "",
            "const $1Drawer: React.FC<T$1Drawer> = ({ open, onClose }) => {",
            "    const [form] = Form.useForm<TFormValues>();",
            "    const [isSubmitting, setIsSubmitting] = useState(false);",
            "",
            "    const onFormFinish = async (values: TFormValues) => {",
            "        try {",
            "            setIsSubmitting(true);",
            "            await new Promise((resolve) => setTimeout(resolve, 1000));",
            "            console.log(values);",
            "        } finally {",
            "            setIsSubmitting(false);",
            "        }",
            "    };",
            "",
            "    useEventListener(\"keydown\", (e) => {",
            "        if (!open) return;",
            "        if ((e.ctrlKey || e.metaKey) && e.key === \"Enter\") form.submit();",
            "    });",
            "",
            "    return (",
            "        <Drawer",
            "            destroyOnClose",
            "            title={",
            "                <header className=\"w-full h-11 px-4 pt-3 pb-2 bg-gray-50 border-b border-gray-100 justify-between items-center inline-flex\">",
            "                    <div className=\"justify-start items-center gap-2.5 flex\">",
            "                        <div className=\"p-1 bg-white rounded-md shadow justify-start items-center gap-2 flex\">",
            "                            <FileText className=\"w-4 h-4 relative text-violet-600\" />",
            "                        </div>",
            "                        <div className=\"justify-start items-center gap-2 flex\">",
            "                            <div className=\"text-gray-900 text-base font-medium font-['Inter'] leading-normal\">$2</div>",
            "                        </div>",
            "                    </div>",
            "                    <X className=\"w-4 h-4 relative text-gray-400\" role=\"button\" tabIndex={0} onClick={onClose} />",
            "                </header>",
            "            }",
            "            footer={",
            "                <footer className=\"rounded-xl flex gap-3 justify-end items-center py-3 border-t border-t-solid border-t-gray-100 absolute bottom-0 left-0 right-0 px-3 bg-white\">",
            "                    <Button onClick={onClose}>",
            "                        Cancel",
            "                    </Button>",
            "                    <Button loading={isSubmitting} htmlType=\"submit\" type=\"primary\" onClick={form.submit}>",
            "                        Update",
            "                        <KeyboardButton className=\"ms-2\" keys={[\"ctrl/⌘\", \"\"]} />",
            "                    </Button>",
            "                </footer>",
            "            }",
            "            className=\"[&_.ant-drawer-header]:p-0 [&_.ant-drawer-body]:p-4 [&_.ant-drawer-body]:pb-14 [&_.ant-drawer-body]:relative\"",
            "            closeIcon={false}",
            "            onClose={onClose}",
            "            open={open}",
            "        >",
            "            <div>",
            "                <Form layout=\"vertical\" form={form} onFinish={onFormFinish}>",
            "                    $3",
            "                </Form>",
            "            </div>",
            "        </Drawer>",
            "    );",
            "};",
            "",
            "export default $1Drawer;"
        ],
        "description": "React Drawer with Form"
    },
}
Enter fullscreen mode Exit fullscreen mode

How to Use

To use this snippet, simply type the prefix "drawer-form" in an empty file, and your IDE will suggest this snippet. Press Enter, and the entire code will be inserted with multiple cursors on the dynamic variables ($1, $2, etc.). Enter the component name, press Tab, and the cursor will shift to the next variable. That's it! This way, you can quickly create multiple drawer components.

How to Create a Code Snippet

To create a custom code snippet in VS Code, follow these steps:

  1. Open the Command Palette:
    • Press Ctrl+Shift+P (Windows/Linux) or Cmd+Shift+P (Mac) to open the Command Palette.
  2. Select 'Preferences: Configure User Snippets':
    • Type and select Preferences: Configure User Snippets.
  3. Choose or Create a Snippet File:
    • Select the language for which you want to create the snippet or choose New Global Snippets file for a global snippet.
  4. Define the Snippet:
    • Add your snippet in the JSON format, specifying the prefix, body, and description. See the example snippet above.

Sharing Snippets with Your Team

  • Workspace Snippets: Save the snippet JSON file in the .vscode folder of your project.
  • Git Repository: Commit the snippet JSON file to your project's repository.
  • Extensions: Create a custom VS Code extension containing your snippets and share it with your team.

By using these methods, you can ensure that your team has access to the same productivity-boosting snippets, making your workflow more efficient and consistent.

Conclusion

By using code snippets, you can significantly reduce the time spent on repetitive tasks, allowing you to focus more on the unique aspects of your project. This practice not only improves productivity but also helps maintain consistency and reduces the chance of errors.

I hope you find this tip useful! Happy coding!

Top comments (0)