Code faster with snippets 🛠

Nicolas Dommanget
3 min readJun 22, 2020

Code faster in React with VS Code or Webstorm and snippets

Unsplash: Joshua Aragon

How many times did you create a React component, rewriting the same code over and over?

What if it was possible to write these lines automatically? You would gain a lot of time. Hopefully, it exists something like that: The snippets.

You may already know what is a snippet, it is a bit of code that is reusable like a template. You can reuse this bit of code every time you need, for example when you create a new component, use a hook…

If you are using a modern editor such as VS Code, Webstorm, … it already exists extension with premade snippets such as:

Feel free to install and test an extension from your editor marketplace. Or you can create your snippets that fit your needs.

I am talking about React snippets as it is my main framework but it exists snippets for most languages and you can create your own.

Create a Snippet

With modern code editors, it is possible to create your snippets. We will see how to do it on VS Code & WebStorm.

VS Code

On VS Code you can find your snippets here:

  • Mac: Code > Preferences > User snippets
  • Windows: File > Preferences > User snippets

You will be asked to select or create a snippet file:

Snippet Menu

We will create a new one call React:

Default Snippet file

A snippet is composed by 3 main things:

  • A prefix: Used to call the snippet from a file
  • A scope: In which type of file the snippet will be called
  • The body: The content of our snippet

We are now able to create our snippets. Let’s create a snippet for React function component:

React functional component snippet

It is possible to use variables such as filename (TM_FILENAME_BASE) in snippets. (VS Code snippet variables doc).

You just have to save the file and you will be able to use the snippet:

Snippet usage

WebStorm

As for VS Code, it is possible to create snippets on WebStorm:

  • Mac: WebStorm > Preferences > Live Templates
  • Windows: File > Preferences > Live Templates

Webstorm has a GUI to provide:

  • Abbreviation
  • Context
  • Description
  • Template text

You just have to click on the “+” icon on right side of the window:

Create Snippet on Webstorm

You just have to fill the fields. We will create the same snippet as with VS Code:

RFC Snippet

As you can see, we try to use a variable between the “$” signs, so you need to provide the variable as follow (WebStorm variables doc):

This variable will provide the file name to the snippet.

We are now able to create and use snippets on VS Code and Webstorm. You will code faster now 🚀

You can find my other articles and follow me here. Thanks for reading, I hope you learned something new today 🚀

--

--

Nicolas Dommanget

Software engineer @mailjet the day, side projects the night.