---
name: js-ts-resource-management
description: "Resource management in JS/TS focusing on memory, event listeners, and async resources."
language: js-ts
---

# JS/TS Resource Management

Best practices for managing memory and system resources in JavaScript and TypeScript.

## Guidelines
- **Automatic Garbage Collection**: Understand that JS handles memory but you must avoid creating unreachable references.
- **Cleanup in Components**: In React, use the cleanup function of `useEffect` to clear timeouts, intervals, and event listeners.
- **Avoid Global Variables**: Global variables stay in memory for the life of the application.
- **Manage Subscriptions**: Use AbortController for cancelling fetch requests or RxJS subscriptions.
- **Stream Large Data**: In Node.js, use Streams for processing large files instead of loading them entirely into memory.
- **Close Database/Network Connections**: Ensure all connections are properly closed when no longer needed, especially in serverless environments.

## Tools & Libraries
- **Chrome DevTools Memory Tab**: For heap snapshots and identifying memory leaks.
- **AbortController**: Standard API for cancelling async tasks.
- **Node.js Streams API**: For efficient resource management in backend.

## Trigger Scenarios
- When implementing timers or event listeners in a long-lived application.
- When processing large datasets or files in Node.js.
- When building a complex SPA (Single Page Application) with many routes and components.
- When a developer reports a memory leak in the browser.

<!-- synapsis-dsai-managed -->
