Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions frontend/react/performance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
---
description: Vibe coding guidelines and architectural constraints for React Performance within the frontend domain.
tags: [react, performance, use, react-compiler, best-practices, architecture, clean-code]
topic: React Performance
complexity: Architect
last_evolution: 2026-03-22
vibe_coding_ready: true
technology: React
domain: frontend
level: Senior/Architect
version: "19+"
ai_role: Senior React Performance Expert
last_updated: 2026-03-22
---

# ⚡ React Performance & Best Practices

[⬆️ Back to Top](#)

# 📖 Context & Scope
- **Primary Goal:** Outline advanced techniques for optimal performance in React 19+.
- **Target Tooling:** Cursor, Windsurf, Antigravity.
- **Tech Stack Version:** React 19+

## 📚 Topics

### 1. Manual Memoization vs React Compiler
**Context:** Avoiding unnecessary re-renders.
#### ❌ Bad Practice
```tsx
import { useMemo, useCallback } from 'react';

function UserList({ users }) {
const sortedUsers = useMemo(() => users.sort(), [users]);
const handleSelect = useCallback((id) => selectUser(id), []);

return (
<ul>
{sortedUsers.map(u => <li key={u.id} onClick={() => handleSelect(u.id)}>{u.name}</li>)}
</ul>
);
}
```
#### ⚠️ Problem
Adding manual `useMemo` and `useCallback` clutters the codebase, introduces dependency array bugs, and makes code harder to refactor.
#### ✅ Best Practice
```tsx
function UserList({ users }) {
const sortedUsers = users.sort();
const handleSelect = (id) => selectUser(id);

return (
<ul>
{sortedUsers.map(u => <li key={u.id} onClick={() => handleSelect(u.id)}>{u.name}</li>)}
</ul>
);
}
```
#### 🚀 Solution
Rely on the **React Compiler** (introduced in React 19+). The compiler automatically memoizes values and functions, meaning manual hooks are largely obsolete and code becomes purely declarative.
- **Performance Note:** The React Compiler analyzes your component structure and injects optimal memoization (similar to SolidJS's granular updates), eliminating the overhead of manual dependency tracking.
- **Security Note:** While the React Compiler does not directly impact security, it ensures components render exactly when their inputs change, reducing side effects that might otherwise expose temporary or stale data to users.

### 2. Resolving Promises During Render
**Context:** Conditionally handling promises without `useEffect` or `useState`.
#### ❌ Bad Practice
```tsx
import { useEffect, useState } from 'react';

function Profile({ profilePromise }) {
const [data, setData] = useState(null);

useEffect(() => {
profilePromise.then(res => setData(res));
}, [profilePromise]);

if (!data) return <p>Loading...</p>;
return <div>{data.name}</div>;
}
```
#### ⚠️ Problem
Using `useEffect` to unwrap promises leads to "waterfalls", unnecessary rendering cycles, and race conditions.
#### ✅ Best Practice
```tsx
import { use, Suspense } from 'react';

function Profile({ profilePromise }) {
const data = use(profilePromise);
return <div>{data.name}</div>;
}

// Parent Usage
// <Suspense fallback={<p>Loading...</p>}>
// <Profile profilePromise={profilePromise} />
// </Suspense>
```
#### 🚀 Solution
Use the `use()` API inside components combined with `<Suspense>`.
- **Performance Note:** `use()` suspends the component rendering if the promise is not resolved. This seamlessly integrates with `<Suspense>`, providing a highly optimized rendering fallback behavior.
- **Security Note:** `use()` can also resolve context, mitigating prop-drilling vulnerabilities and ensuring components securely consume data directly from contexts they are explicitly authorized for. Always sanitize any text coming from external APIs before rendering.

[⬆️ Back to Top](#)
83 changes: 83 additions & 0 deletions frontend/react/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
---
description: Vibe coding guidelines and architectural constraints for React within the frontend domain.
tags: [react, best-practices, architecture, clean-code, scalable-code, modern-react, server-components]
topic: React
complexity: Architect
last_evolution: 2026-03-22
vibe_coding_ready: true
technology: React
domain: frontend
level: Senior/Architect
version: "19+"
ai_role: Senior React Expert
last_updated: 2026-03-22
---

# ⚛️ React Production-Ready Best Practices

# 📖 Context & Scope
- **Primary Goal:** Provide architectural best practices for modern React development.
- **Target Tooling:** Cursor, Windsurf, Antigravity.
- **Tech Stack Version:** React 19+

> [!NOTE]
> When building React applications in 2026, always implement the React best practices described here to ensure maximum performance, maintainability, and security.

## 🏗 Architecture Principles

- Adhere to the defined [Architectural Patterns](../../architectures/readme.md) when building applications.
- Strongly prefer **Feature Sliced Design (FSD)** for applications scaling across multiple teams.

## 🚀 I. Basics & Popular

### 1. Direct DOM Manipulation
**Context:** Updating elements in a React component.
#### ❌ Bad Practice
```tsx
function Component() {
const handleClick = () => {
document.getElementById('my-element').style.color = 'red';
};
return <div id="my-element" onClick={handleClick}>Click me</div>;
}
```
#### ⚠️ Problem
Direct DOM manipulation bypasses React's virtual DOM, causing inconsistencies between the actual DOM and React's internal state.
#### ✅ Best Practice
```tsx
function Component() {
const [isActive, setIsActive] = useState(false);
return (
<div
style={{ color: isActive ? 'red' : 'black' }}
onClick={() => setIsActive(!isActive)}
>
Click me
</div>
);
}
```
#### 🚀 Solution
Always use state and props to drive the UI. React uses a virtual DOM to efficiently update the real DOM based on state changes.
- **Performance Note:** React's virtual DOM diffing algorithm is highly optimized. Bypassing it can lead to forced synchronous layouts and jank.
- **Security Note:** Direct DOM manipulation can open up Cross-Site Scripting (XSS) vulnerabilities if user input is not properly sanitized before being inserted into the DOM.

### 2. Large Component Files
**Context:** Managing component complexity.
#### ❌ Bad Practice
A single 2000-line file containing the entire page's logic and UI.
#### ⚠️ Problem
Massive components are difficult to read, test, and maintain. They often violate the Single Responsibility Principle.
#### ✅ Best Practice
Break down the UI into smaller, reusable components, each with a single responsibility.
#### 🚀 Solution
Extract logic into custom hooks and presentational elements into separate files.

## 📚 Specialized Topics

For further reading, please refer to the following specialized guides:

- [🔄 State Management](./state-management.md)
- [⚡ Performance](./performance.md)

[⬆️ Back to Top](#)
89 changes: 89 additions & 0 deletions frontend/react/state-management.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
---
description: Vibe coding guidelines and architectural constraints for React State Management within the frontend domain.
tags: [react, state-management, server-actions, best-practices, architecture, clean-code]
topic: React State Management
complexity: Architect
last_evolution: 2026-03-22
vibe_coding_ready: true
technology: React
domain: frontend
level: Senior/Architect
version: "19+"
ai_role: Senior React State Management Expert
last_updated: 2026-03-22
---

# 🔄 React State Management & Server Actions Best Practices

[⬆️ Back to Top](#)

# 📖 Context & Scope
- **Primary Goal:** Provide best practices for managing state, including React 19+ Server Actions.
- **Target Tooling:** Cursor, Windsurf, Antigravity.
- **Tech Stack Version:** React 19+

## 📚 Topics

### 1. Handling Async Actions (Forms)
**Context:** Managing state updates triggered by form submissions or asynchronous operations.
#### ❌ Bad Practice
```tsx
import { useState } from 'react';

function Form() {
const [isPending, setIsPending] = useState(false);
const [error, setError] = useState(null);

const handleSubmit = async (e) => {
e.preventDefault();
setIsPending(true);
setError(null);
try {
await saveAction(new FormData(e.target));
} catch (err) {
setError(err);
} finally {
setIsPending(false);
}
};

return <form onSubmit={handleSubmit}>...</form>;
}
```
#### ⚠️ Problem
Manually managing `isPending` and error states is repetitive and prone to race conditions, especially when multiple requests are fired.
#### ✅ Best Practice
```tsx
import { useActionState } from 'react';
import { saveAction } from './actions';

function Form() {
const [error, submitAction, isPending] = useActionState(saveAction, null);

return (
<form action={submitAction}>
{error && <p>{error.message}</p>}
<button disabled={isPending}>Submit</button>
</form>
);
}
```
#### 🚀 Solution
Use the `useActionState` Hook (React 19+) for seamless action state management.
- **Performance Note:** `useActionState` effectively handles race conditions by ensuring only the latest action state is applied to the UI, optimizing rendering cycles.
- **Security Note:** Form actions seamlessly interact with Server Actions. Ensure that `saveAction` strictly validates input server-side to prevent malicious payloads, and use CSRF tokens if required by your framework.

### 2. Using Global State Naively
**Context:** Storing local component UI state in a global store (e.g., Redux, Zustand).
#### ❌ Bad Practice
Putting a dropdown's `isOpen` state into the global Redux store.
#### ⚠️ Problem
Unnecessary global re-renders and bloated global state size.
#### ✅ Best Practice
Use `useState` or `useReducer` for UI state that belongs locally to a component tree.
#### 🚀 Solution
Only elevate state to a global store when it is shared across multiple disjoint component branches.
- **Performance Note:** Global state updates trigger broad change detection and React reconciliation. Minimizing global state keeps updates localized and fast.
- **Security Note:** Do not store sensitive access tokens (e.g., JWT) in unencrypted global state (like localStorage/Redux state) that may persist across sessions or expose them to XSS attacks. Prefer HttpOnly cookies.

[⬆️ Back to Top](#)
1 change: 1 addition & 0 deletions frontend/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,6 @@ This folder acts as a container for documentation around the following technolog
- [Angular](./angular/readme.md)
- [JavaScript](./javascript/readme.md)
- [TypeScript](./typescript/readme.md)
- [React](./react/readme.md)
- [SolidJS](./solidjs/readme.md)
- [Qwik](./qwik/readme.md)
Loading