---
title: "Building Custom JavaScript Decorators"
description: "Hey there, fellow developers! Today, we're diving into the fascinating world of JavaScript decorators. Now, before you roll your eyes and think, \"Not another…"
url: https://www.danny.engineering/article/building-custom-javascript-decorators
author: Danny
published: 2024-04-09T00:00:00.000Z
updated: 2024-08-12T20:29:00.000Z
tags: ["Javascript"]
---

# Building Custom JavaScript Decorators

# Building Custom JavaScript Decorators


## Introduction


Hey there, fellow developers! Today, we're diving into the fascinating world of JavaScript decorators. Now, before you roll your eyes and think, "Not another complex topic," let me tell you—decorators can be an absolute game-changer in building cleaner, more readable code that enhances your front-end applications, especially when working with React and TypeScript. So grab a cup of coffee, sit back, and let's break this down together.


## What Are Decorators Anyway?


In simple terms, decorators are functions that modify the behavior of a class or a method. They allow you to wrap another function, altering its functionality in a reusable way. Imagine them like gift-wrap for your favorite goodies: they add a layer of functionality without changing the gift (the original method or class logic) itself. Decorators are often used in frameworks like Angular, but we can absolutely harness their power in React and TypeScript too.


### Why Use Decorators?

1. **Code Reusability**: Write code once and apply it wherever you need it.
2. **Separation of Concerns**: Keep your core logic clean and separate additional functionality cleanly.
3. **Enhanced Readability**: Decorators can make it clearer what a method is doing at a glance.

But before we get ahead of ourselves, let’s dive into how we can create custom decorators in JavaScript.


## Creating a Basic Decorator


Let’s kick things off with a simple example of a method decorator. Here’s a basic decorator that logs the method name and arguments each time it gets called.


```javascript
function LogMethod(target, propertyKey, descriptor) {
    const originalMethod = descriptor.value;

    descriptor.value = function(...args) {
        console.log(`Calling ${propertyKey} with arguments: ${JSON.stringify(args)}`);
        return originalMethod.apply(this, args);
    };

    return descriptor;
}
```


### Breaking Down the Code

- **target**: The prototype of the class for static methods or the instance of the class for instance methods.
- **propertyKey**: The name of the method being decorated.
- **descriptor**: The property descriptor for the method (think of it as the method’s metadata).

In this example, we store the original method in `originalMethod`, replace its implementation with a new function that logs the call, and then call the original method.


## Applying the Decorator in a Class


Now let’s see how we can apply this `LogMethod` decorator to a class.


```javascript
class User {
    @LogMethod
    login(username) {
        console.log(`${username} has logged in.`);
    }
}

const user = new User();
user.login('JohnDoe'); // This will log the method details before the login message.
```


### What Happens Here?


When you call `user.login('JohnDoe')`, the decorator intercepts the call. You’ll see logs about the method invocation before the actual login message appears in the console. Pretty neat, right?


## Real-World Application: A Data Fetcher


Let’s take this a step further and think of a real-world application scenario where a decorator might be super helpful. Imagine you have multiple API methods that need caching to reduce server requests. Here’s how you can build a caching decorator:


```javascript
function Cache(timeout = 5000) {
    const cache = new Map();
  
    return function(target, propertyKey, descriptor) {
        const originalMethod = descriptor.value;

        descriptor.value = async function(...args) {
            const cacheKey = JSON.stringify(args);
            if (cache.has(cacheKey)) {
                console.log(`Returning cached result for ${propertyKey}`);
                return cache.get(cacheKey);
            }
            const result = await originalMethod.apply(this, args);
            cache.set(cacheKey, result);
            setTimeout(() => cache.delete(cacheKey), timeout);
            return result;
        };

        return descriptor;
    };
}
```


### Using the Cache Decorator


Now, you can decorate your data-fetching methods with this caching logic efficiently:


```javascript
class APIService {
    @Cache(10000)
    async fetchData(apiUrl) {
        const response = await fetch(apiUrl);
        return response.json();
    }
}

const apiService = new APIService();
apiService.fetchData('https://jsonplaceholder.typicode.com/posts/1').then(console.log);
// Subsequent calls with the same URL within 10 seconds will return cached data.
```


## Best Practices and Common Pitfalls


Before you think you’re ready to go full decorator-crazy, here are some tips to keep in mind:

1. **Keep Decorators Simple**: They should enhance functionality without making your code too complex. If it feels overly complicated, you might be doing too much in one decorator.
2. **Test Thoroughly**: Since decorators modify behavior, ensure you test them isolated from rest of your application to understand their effects.
3. **Document Your Decorators**: Like any piece of reusable code, well-documented decorators help other developers (or your future self) understand their purpose and usage quickly.
4. **Integrate User Needs**: Always think about how your decorators affect end-users. User-friendly design should integrate seamlessly with your code structure.

## Conclusion


And there you have it! Custom decorators can help you write cleaner, more maintainable, and scalable code in your React and TypeScript applications. Whether you’re enhancing logging, implementing caching, or even adding authentication, decorators allow you to encapsulate behavior and promote code reuse.


I hope this article shines a light on decorators and inspires you to explore this amazing JavaScript feature further. Happy coding! If you enjoyed this content and want to dive deeper into practical techniques that make frontend development both fun and effective, stay tuned for more articles. Let’s continue this coding journey together!
