Hive Community

All posts

Deep, practical engineering stories — browse everything.

Vue 3 Composition API: Complete Guide and Best Practices

Vue 3’s Composition API provides better code organization. Here’s how to use it effectively. Setup import { ref, computed, watch } from 'vue'; export default { setup() { const count = ref(0); const doubled = computed(() => count.value * 2); watch(count, (newVal) => { console.log('Count changed:', newVal); }); return { count, doubled }; } } Script Setup <script setup> import { ref, computed } from 'vue'; const count = ref(0); const doubled = computed(() => count.value * 2); function increment() { count.value++; } </script> Composables // useCounter.js import { ref } from 'vue'; export function useCounter(initialValue = 0) { const count = ref(initialValue); const increment = () => count.value++; const decrement = () => count.value--; return { count, increment, decrement }; } Best Practices Use composables for reusability Keep setup functions focused Use script setup syntax Organize by feature Extract complex logic Conclusion Vue 3 Composition API enables better code organization! 🎯

Read

JavaScript Closures Explained: Understanding Scope and Memory

Closures are fundamental to JavaScript. Here’s how they work and when to use them. What is a Closure? A closure gives you access to an outer function’s scope from an inner function. function outer() { const name = 'JavaScript'; function inner() { console.log(name); // Accesses outer scope } return inner; } const innerFunc = outer(); innerFunc(); // "JavaScript" Common Patterns Module Pattern const counter = (function() { let count = 0; return { increment: () => ++count, decrement: () => --count, getCount: () => count }; })(); Function Factories function createMultiplier(multiplier) { return function(number) { return number * multiplier; }; } const double = createMultiplier(2); double(5); // 10 Common Pitfalls Loop with Closures // Bad: All log same value for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); // 3, 3, 3 } // Good: Use let or IIFE for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); // 0, 1, 2 } Best Practices Understand scope chain Avoid memory leaks Use closures for encapsulation Be careful in loops Use modern alternatives when possible Conclusion Master closures to write better JavaScript! 🔒

Read

CSS Grid vs Flexbox: When to Use Which

CSS Grid and Flexbox serve different purposes. Here’s when to use each. Flexbox Use for One-Dimensional Layouts .navbar { display: flex; justify-content: space-between; align-items: center; } Common Use Cases Navigation bars Centering content Flexible components Equal height columns CSS Grid Use for Two-Dimensional Layouts .container { display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: auto; gap: 20px; } Common Use Cases Page layouts Complex grids Card layouts Responsive designs When to Use Both .container { display: grid; grid-template-columns: 1fr 3fr; } .sidebar { display: flex; flex-direction: column; } Best Practices Use Flexbox for components Use Grid for layouts Combine both when needed Consider browser support Test responsiveness Conclusion Choose the right tool for the job! 🎨

Read

Docker Best Practices: Building Efficient Images

Building efficient Docker images requires following best practices. Here’s how. 1. Use Multi-Stage Builds # Build stage FROM node:18 AS builder WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . RUN npm run build # Production stage FROM node:18-alpine WORKDIR /app COPY --from=builder /app/dist ./dist COPY --from=builder /app/node_modules ./node_modules CMD ["node", "dist/index.js"] 2. Layer Caching # Bad: Changes invalidate cache COPY . . RUN npm install # Good: Dependencies cached COPY package*.json ./ RUN npm install COPY . . 3. Use .dockerignore node_modules .git .env dist *.log 4. Minimize Layers # Bad: Multiple layers RUN apt-get update RUN apt-get install -y python RUN apt-get install -y git # Good: Single layer RUN apt-get update && \ apt-get install -y python git && \ rm -rf /var/lib/apt/lists/* 5. Use Specific Tags # Bad: Latest tag FROM node:latest # Good: Specific version FROM node:18.17.0-alpine Best Practices Multi-stage builds Optimize layer order Use .dockerignore Minimize image size Security scanning Conclusion Build efficient Docker images! 🐳

Read

Redis Caching Strategies: Patterns and Best Practices

Redis is powerful for caching. Here are effective caching strategies. Cache-Aside Pattern async function getUser(id) { // Check cache let user = await redis.get(`user:${id}`); if (user) { return JSON.parse(user); } // Cache miss - fetch from DB user = await db.query('SELECT * FROM users WHERE id = ?', [id]); // Store in cache await redis.setex(`user:${id}`, 3600, JSON.stringify(user)); return user; } Write-Through Pattern async function updateUser(id, data) { // Update database const user = await db.update('users', id, data); // Update cache await redis.setex(`user:${id}`, 3600, JSON.stringify(user)); return user; } Cache Invalidation async function deleteUser(id) { // Delete from database await db.delete('users', id); // Invalidate cache await redis.del(`user:${id}`); } Best Practices Set appropriate TTL Handle cache misses Invalidate properly Monitor cache hit rate Use consistent key patterns Conclusion Implement effective Redis caching strategies! 🔴

Read

MongoDB Query Optimization: Indexing and Performance Tips

Optimizing MongoDB queries is essential for performance. Here’s how. Indexing Create Indexes // Single field index db.users.createIndex({ email: 1 }); // Compound index db.users.createIndex({ status: 1, createdAt: -1 }); // Text index db.posts.createIndex({ title: "text", content: "text" }); Explain Queries db.users.find({ email: "[email protected]" }).explain("executionStats"); Query Optimization Use Projection // Bad: Fetches all fields db.users.find({ status: "active" }); // Good: Only needed fields db.users.find( { status: "active" }, { name: 1, email: 1, _id: 0 } ); Limit Results db.users.find({ status: "active" }) .limit(10) .sort({ createdAt: -1 }); Best Practices Create appropriate indexes Use projection Limit result sets Avoid $regex without index Monitor slow queries Conclusion Optimize MongoDB for better performance! 🍃

Read

Elasticsearch Basics: Getting Started with Search

Elasticsearch is powerful for search. Here’s how to get started. Basic Operations Create Index await client.indices.create({ index: 'users', body: { mappings: { properties: { name: { type: 'text' }, email: { type: 'keyword' }, age: { type: 'integer' } } } } }); Index Document await client.index({ index: 'users', id: '1', body: { name: 'John Doe', email: '[email protected]', age: 30 } }); Search const result = await client.search({ index: 'users', body: { query: { match: { name: 'John' } } } }); Best Practices Design mappings carefully Use appropriate analyzers Optimize queries Monitor cluster health Backup regularly Conclusion Master Elasticsearch for powerful search! 🔍

Read

RabbitMQ Message Queues: Patterns and Implementation

RabbitMQ enables reliable message queuing. Here’s how to use it effectively. Basic Setup Producer const amqp = require('amqplib'); async function sendMessage() { const connection = await amqp.connect('amqp://localhost'); const channel = await connection.createChannel(); const queue = 'tasks'; const message = 'Hello RabbitMQ!'; await channel.assertQueue(queue, { durable: true }); channel.sendToQueue(queue, Buffer.from(message), { persistent: true }); console.log("Sent:", message); await channel.close(); await connection.close(); } Consumer async function receiveMessage() { const connection = await amqp.connect('amqp://localhost'); const channel = await connection.createChannel(); const queue = 'tasks'; await channel.assertQueue(queue, { durable: true }); channel.consume(queue, (msg) => { if (msg) { console.log("Received:", msg.content.toString()); channel.ack(msg); } }); } Patterns Work Queues // Distribute tasks among workers channel.prefetch(1); // Fair dispatch Pub/Sub // Exchange for broadcasting await channel.assertExchange('logs', 'fanout', { durable: false }); channel.publish('logs', '', Buffer.from(message)); Best Practices Use durable queues Acknowledge messages Handle errors Monitor queues Use exchanges for routing Conclusion Implement reliable message queuing with RabbitMQ! 🐰

Read

PostgreSQL Performance Tuning: Optimization Guide

PostgreSQL performance tuning requires understanding configuration and queries. Here’s a guide. Configuration Tuning postgresql.conf # Memory settings shared_buffers = 256MB effective_cache_size = 1GB work_mem = 16MB # Connection settings max_connections = 100 # Query planner random_page_cost = 1.1 Query Optimization Use EXPLAIN ANALYZE EXPLAIN ANALYZE SELECT * FROM users WHERE email = '[email protected]'; Indexing -- B-tree index CREATE INDEX idx_user_email ON users(email); -- Partial index CREATE INDEX idx_active_users ON users(email) WHERE status = 'active'; -- Composite index CREATE INDEX idx_user_status_created ON users(status, created_at); Best Practices Analyze query plans Create appropriate indexes Use connection pooling Monitor slow queries Vacuum regularly Conclusion Tune PostgreSQL for optimal performance! 🐘

Read