Skip to content
coding-standards logo

Coding Standards & Best Practices

coding-standards

Universal coding standards and best practices for TypeScript, JavaScript, React, and Node.js. Use when: writing code, reviewing code quality, establishing conventions. Focuses on modern patterns, explicit conventions, and rationale for best practices.

SKILL.md

Full skill instructions

Coding Standards & Best Practices

Modern coding standards applicable across TypeScript, JavaScript, React, and Node.js projects.


Quick Navigation

If you need...MANDATORY READ WHEN...File
Type patternsWRITING TYPESreferences/​type-patterns.md
React patternsWRITING COMPONENTSreferences/​react-patterns.md
API patternsDESIGNING APISreferences/​api-patterns.md
Testing patternsWRITING TESTSreferences/​testing-patterns.md

Core Principles

1. Readability First

WHY: Code is read 10x more than written. Optimize for the reader.

Practices:

  • Self-documenting code preferred over comments
  • Descriptive variable and function names
  • Consistent formatting (use linter/​formatter)
  • Clear intent over clever tricks

Recognition: "Would a new team member understand this without explanation?"

2. Immutability Pattern (CRITICAL)

WHY: Prevents stale closures, makes state predictable, enables React optimizations.

✅ ALWAYS use spread operator:

const updatedUser = { ...user, name: 'New Name' }
const updatedArray = [...items, newItem]

❌ NEVER mutate directly:

user.name = 'New Name'  // BAD - causes bugs
items.push(newItem)     // BAD - breaks React optimizations

Best practice: Use Lodash (cloneDeep), Immer, or structuredClone for deep objects.

3. Functional Updates for State

WHY: Prevents stale closure bugs in async scenarios.

✅ GOOD (functional update):

setCount(prev => prev + 1)
setData(prev => ({ ...prev, field: value }))

❌ BAD (direct reference - can be stale):

setCount(count + 1)     // May use stale value
setData({ ...data, field: value })  // Can miss updates

4. Comprehensive Error Handling

WHY: Unhandled errors crash processes, cause bad UX, make debugging impossible.

✅ GOOD pattern:

async function fetchData(url: string) {
  try {
    const response = await fetch(url)
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    return await response.json()
  } catch (error) {
    console.error('Fetch failed:', error)
    throw new Error('Failed to fetch data')
  }
}

❌ BAD (no error handling):

async function fetchData(url) {
  const response = await fetch(url)
  return response.json()  // Crashes on network failure
}

5. Parallel Async Execution

WHY: Sequential awaits waste time. Parallel execution is faster.

✅ GOOD (parallel when possible):

const [users, markets, stats] = await Promise.all([
  fetchUsers(),
  fetchMarkets(),
  fetchStats()
])

❌ BAD (sequential when unnecessary):

const users = await fetchUsers()    // Waits 100ms
const markets = await fetchMarkets() // Waits 100ms (total: 200ms)
const stats = await fetchStats()     // Waits 100ms (total: 300ms)

Recognition: "Can these operations run in parallel?" → Use Promise.all

6. Type Safety Over Convenience

WHY: Types catch bugs at compile-time, serve as documentation, enable refactoring.

✅ GOOD (proper types):

interface Market {
  id: string
  name: string
  status: 'active' | 'resolved' | 'closed'
}

function getMarket(id: string): Promise<Market> { }

❌ BAD (using any):

function getMarket(id: any): Promise<any> { }

Recognition: "Could I use a more specific type?" → Always prefer specificity


Naming Conventions

Variables and Functions

✅ GOOD (descriptive, camelCase):

const marketSearchQuery = 'election'
const isUserAuthenticated = true
const totalRevenue = 1000

async function fetchMarketData(marketId: string) { }
function calculateSimilarity(a: number[], b: number[]) { }

❌ BAD (unclear, abbreviated):

const q = 'election'
const flag = true
const x = 1000

async function market(id: string) { }
function similarity(a, b) { }

Boolean Variables

Prefix with is, has, should, can:

const isLoading = true
const hasPermission = false
const shouldRetry = true
const canEdit = true

Constants

Use UPPER_SNAKE_CASE for true constants (never reassigned):

const MAX_RETRIES = 3
const DEFAULT_TIMEOUT_MS = 5000
const API_BASE_URL = 'https://api.example.com'

Code Organization

File Structure Preference

src/
├── components/         # React components
│   ├── ui/            # Generic, reusable
│   └── features/      # Feature-specific
├── hooks/             # Custom React hooks
├── lib/               # Utilities and helpers
│   ├── api/          # API clients
│   ├── utils/        # Helper functions
│   └── constants/    # Constants
├── types/             # TypeScript types
└── styles/            # Global styles

File Naming

TypePatternExample
ComponentsPascalCaseButton.tsx, MarketCard.tsx
HookscamelCase with use prefixuseAuth.ts, useDebounce.ts
UtilitiescamelCaseformatDate.ts, calculateTotal.ts
TypescamelCase with .types suffixmarket.types.ts
ConstantscamelCase with constants suffixapi.constants.ts

Common Anti-Patterns

Anti-Pattern 1: Magic Numbers

❌ BAD:

if (retryCount > 3) { }
setTimeout(callback, 500)

✅ GOOD:

const MAX_RETRIES = 3
const DEBOUNCE_DELAY_MS = 500

if (retryCount > MAX_RETRIES) { }
setTimeout(callback, DEBOUNCE_DELAY_MS)

Anti-Pattern 2: Deep Nesting

❌ BAD (5+ levels):

if (user) {
  if (user.isAdmin) {
    if (market) {
      if (market.isActive) {
        if (hasPermission) {
          // Do something
        }
      }
    }
  }
}

✅ GOOD (early returns):

if (!user) return
if (!user.isAdmin) return
if (!market) return
if (!market.isActive) return
if (!hasPermission) return

// Do something

Anti-Pattern 3: Console.log in Production

❌ BAD:

console.log('User logged in', user)
console.error('Error occurred', error)

✅ GOOD:

// Use proper logging library
logger.info('User logged in', { userId: user.id })
logger.error('Error occurred', { error, context })

Anti-Pattern 4: Ignoring Type Errors

❌ BAD:

// @ts-ignore
const data = JSON.parse uncertain

✅ GOOD:

const data = JSON.parse uncertain as unknown as ExpectedType
// Or use zod/​joi for validation

Performance Best Practices

Memoization

Use for:

  • Expensive computations (useMemo)
  • Functions passed to children (useCallback)
  • Pure components (React.memo)
const sortedMarkets = useMemo(() => {
  return markets.sort((a, b) => b.volume - a.volume)
}, [markets])

const handleSearch = useCallback((query: string) => {
  setSearchQuery(query)
}, [])

Lazy Loading

Use for:

  • Heavy components (lazy, Suspense)
  • Route-based code splitting
  • Non-critical features
const HeavyChart = lazy(() => import('./​HeavyChart'))

<Suspense fallback={<ChartSkeleton />}>
  <HeavyChart data={data} />
</​Suspense>

Verification Checklist

Before considering code complete:

  • Immutability pattern used (spread operators)
  • Functional state updates (prev => pattern)
  • Comprehensive error handling
  • Type-safe (no any without justification)
  • Parallel async execution where possible
  • Descriptive naming (self-documenting)
  • No console.log in production code
  • No magic numbers (use constants)
  • Early returns over deep nesting
  • Performance optimizations applied

Integration with Other Skills

This skill integrates with:

  • frontend-patterns - React/​Next.js specific patterns
  • backend-patterns - API and database patterns
  • tdd-workflow - Testing standards
  • verify - Quality gate verification

Recognition: "Am I following WHY-based best practices?" → If you're doing something "because that's how it's done," you're missing the rationale.

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View