Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save EuFreela/4625a3cebdcfc22653427f4d0af576b3 to your computer and use it in GitHub Desktop.
Save EuFreela/4625a3cebdcfc22653427f4d0af576b3 to your computer and use it in GitHub Desktop.
React + TypeScript Advanced Web Development Cheat Sheet - 2025

🚀 Advanced Cheat Sheet: React + TypeScript Web Development

1️⃣ Validation

  • Zod / Yup for schema validation:

    import { z } from 'zod';
    
    const userSchema = z.object({
      name: z.string().min(1),
      email: z.string().email(),
    });
  • React Hook Form + Zod Integration:

    const { register, handleSubmit, formState: { errors } } = useForm<YourType>({
      resolver: zodResolver(yourSchema),
    });
  • Client + Server Validation: Validate on both client and server to prevent tampering.

  • Custom Validators: Always sanitize and validate inputs for URL, email, and number types.


2️⃣ Immutability

  • State Management:

    • Use useState and useReducer with immutable patterns.

    • Avoid directly mutating state:

      // ❌ Avoid
      state.items.push(newItem);
      
      // ✅ Instead
      setState(prev => [...prev.items, newItem]);
  • Libraries:

    • Use Immer or Zustand with immutability helpers.
  • TypeScript Tip: Use Readonly<T> to enforce immutability where needed.


3️⃣ Concurrency (Parallelism)

  • React 18 Concurrent Features:

    • Use useTransition to keep UI responsive during state updates.
    • Use Suspense + lazy() for data fetching & component loading.
  • Parallel Data Fetching:

    const [data1, data2] = await Promise.all([
      fetchData1(),
      fetchData2(),
    ]);
  • Web Workers for heavy computations:

    • Offload CPU-heavy tasks to web workers using workerize-loader.

4️⃣ Scalability

  • Folder Structure (Example):

    src/
      modules/
        user/
          components/
          services/
          hooks/
          pages/
        admin/
      shared/
        components/
        hooks/
        utils/
      router/
      store/
      styles/
      config/
    
  • Modularization:

    • Split features into self-contained modules.
    • Use lazy loading for large modules.
  • Global State:

    • Use Zustand, Redux Toolkit, or Recoil with code splitting support.
  • Code Splitting:

    const AdminPanel = React.lazy(() => import('./AdminPanel'));
  • API Layer:

    • Centralize your API calls with Axios + TypeScript interfaces.

5️⃣ Security

  • XSS Protection:

    • Use {} for binding, avoid dangerouslySetInnerHTML unless sanitized with DOMPurify.
  • URL & Input Validation:

    const isValidURL = (url: string) => {
      try {
        const parsed = new URL(url);
        return ['http:', 'https:'].includes(parsed.protocol);
      } catch {
        return false;
      }
    };
  • Dependency Monitoring:

    • Use Snyk or npm audit:

      npx snyk test
      npm audit fix
  • Secure JSON Embedding:

    <script>
      window.__PRELOADED_STATE__ = JSON.stringify(state).replace(/</g, '\\u003c');
    </script>
  • Linters + Pre-Commit Hooks:

    • Setup ESLint + eslint-plugin-security.
    • Use Husky for pre-commit checks.
  • Latest React Version:

    • Stay updated with npm outdated.
  • HTTPS & Content Security Policy (CSP):

    • Ensure your app runs under HTTPS.
    • Configure strict CSP headers.

Bonus 🛠️ TypeScript Practices

  • Strong Typing:

    • Never use any. Use unknown + narrowing or create types/interfaces.
  • Props & State:

    interface UserProps {
      id: string;
      name: string;
    }
    
    const UserCard: React.FC<UserProps> = ({ id, name }) => (
      <div>{name}</div>
    );
  • Custom Hooks Typing:

    function useUser(id: string): { data: User | null; loading: boolean } {
      // ...
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment