Taha

Write Better Frontend Components with This Tip

Components are the basic building blocks used in modern frontend frameworks like React, Vue, and Svelte. Well-written components can improve the overall structure of your app and make it clean and maintainable.

It's likely that you've heard about the presentational and container components pattern. In some cases, this might be a helpful pattern to use — but not always. I've used this pattern throughout a complex project and I've ended up with a lot of boiler-platy components.

After writing lots of components and building complex frontend applications, I realized that we have only two types of components: UI general-purpose components and app-specific components.

Understanding what they are for and how to write them will help you design better components and ultimately better application architecture.

UI general-purpose components

They are pure UI components that are not made for a specific application. They are used for general UI elements like multi-select inputs, modal boxes, pagination links, etc.

So these components:

  • Can be shared easily from project to project
  • Don’t depend on the state of the app
  • Don't have access to global data
  • Don't make AJAX requests
  • Just take props and emit events
  • Are good for npm packages

So UI libraries like Vuetify and Material-UI are considered UI general-purpose components.

App-specific components

They are components that you implement specifically for your app, and it doesn't make sense to use them somewhere else.

These components:

  • Can be used only inside your app
  • Depend on the state of your app
  • Can have access to global data and use state management libraries like Vuex and Redux
  • Can make AJAX requests directly
  • Can use specific terminologies based on the app's domain — so name variables/functions whatever you want
  • Can be reused throughout your app, but they don't have to
  • Can take props and emit events

A good example is a form component. This component will only work inside your app. It can render its fields based on the state of your app, submit its data directly with an AJAX request, and be reused when updating the data instead of creating it.

So the key to writing better components is to not confuse the two component types. For example, you don't have to create a single component called Form and reuse it for all forms in your app. Instead create as many form components (with specific fields) as you need.

Taha Shashtari

I'm Taha Shashtari, a full-stack web developer. Building for the web is my passion. Teaching people how to do that is what I like the most. I like to explore new techniques and tools to help me and others write better code.

Subscribe to get latest updates about my work
©2024 Taha Shashtari. All rights reserved.