React Pro Tip: Use code snippets to increase your productivity and write better code

Code snippets are templates that make it easier to input repeating code patterns such as statements, React components etc. You can start typing a small prefix e.g. and press Tab or select one of the suggestions to expand it to a multi-line snippet, as shown above.

I really like code snippets, for a variety of reasons:

  • They save time (duh!), since typing 5 characters is faster than typing 50.
  • The help avoid typos and common mistakes, like forgetting to , forgetting the etc. which can sometimes lead to rather cryptic errors.
  • They can help enforce coding conventions and maintain consistency across the codebase e.g. you can use a code snippet to ensure that name of the exported component matches the filename ( exports ).
  • By eliminating the need to type boilerplate code, they help avoid the frustration of typing and dozens of times, and thereby encourage you to write several small single-responsibility components .

Editors like Visual Studio Code make it really easy to create custom code snippets. There are also several extensions that provide code snippets for Javascript, ES6 and React.

I’ve used many of these extensions in the past, but over time I’ve created a set of custom snippets (inspired from existing ones) that are optimized to work well with VS Code’s Intellisense. I recently published them as an extension, and you can download them here:

To enable code completion for filenames and modules, you’ll have to add this to your User Settings:

Following are some of the snippets I find most useful. The rest are documented on the extension page.

: ES6 named imports

  • Notice how you can type the module/file name first. As you start typing, it is auto-completed.
  • Then, as you start typing inside the , the item name is auto-completed, since the editor knows where you're importing from.

: ES6 default import

  • If you’re importing from a relative path, it’s auto-completed as you type.
  • If the imported item’s name is same as the filename, it can be auto-completed by the editor too, which is neat!

: Import React & Component

  • To import just , use .

: Stateless component

  • The name of the file is used as the component name, and can be modified if required.
  • If the component has no props, make sure to delete the .
  • For a stateless component without a statement, use .

: Component class (with )

  • The name of the file is used as the component name, and can be modified if required.
  • To create a component class without the , use .

: Redux container component

While you may or may not find this set of snippets particularly useful, you should definitely look for ones that suit your use case, or consider writing your own. And if you’re part of a team, you should consider having a common set of snippets everyone can use.

Founder, Jovian