Logo React Hooks Composition

React Hooks Composition

Cộng đồng
bobmatnyc
react-hooks-composition

Advanced React hooks composition patterns - SWR integration, debounced search, memoized contexts, state machines, and performance optimization

Tổng quan

Nhà phát hànhbobmatnyc
Kho mãclaude-mpm-skills
Tên kỹ năngreact-hooks-composition
Sao
75
Bản fork
19
Tệp đi kèm
4
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI là Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • 4 tệp đi kèm

    Các tập lệnh, mẫu và tài liệu tham khảo mà mô hình có thể đọc khi làm việc. Các tệp chỉ cho phép đọc và không bao giờ được thực thi.

  • Mã nguồn mở

    Được bobmatnyc công bố trên GitHub. Hãy đọc nội dung nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI React Hooks Composition trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL thư mục kỹ năng bên dưới và xác nhận.
    https://github.com/bobmatnyc/claude-mpm-skills/tree/main/toolchains/javascript/frameworks/react/react-hooks-composition
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/bobmatnyc/claude-mpm-skills.git /tmp/claude-mpm-skills
mkdir -p .claude/skills
cp -r /tmp/claude-mpm-skills/toolchains/javascript/frameworks/react/react-hooks-composition .claude/skills/react-hooks-composition
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật React Hooks Composition trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự tải React Hooks Composition ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên React Hooks Composition không bị giới hạn ở mô hình mà kỹ năng này được viết cho. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên kỹ năng chưa dùng không tốn chi phí.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

React Hooks Composition Patterns

Overview

Advanced patterns for composing React hooks to create maintainable, performant, and type-safe custom hooks. Covers SWR integration, debounced search, memoized contexts, and state machine patterns.

Key Concepts:

  • Conditional SWR fetching with null keys
  • Debounced state with dual loading indicators
  • Memoized context providers to prevent re-renders
  • State machine pattern for predictable UI states
  • Pure helper functions for testability

Pattern 1: SWR Hook Composition with Conditional Fetching

The Pattern

Compose SWR with conditional logic, data transformation, and pure helper functions.

typescript
import useSWR from 'swr';
import { useMemo } from 'react';

// Type definitions
interface MapboxSuggestion {
  name: string;
  mapbox_id: string;
  context?: {
    country?: {
      country_code: string;
    };
  };
}

interface MapboxSuggestResponse {
  suggestions: MapboxSuggestion[];
}

interface LocationSuggestion {
  id: string;
  displayName: string;
  region: string;
}

// Custom hook with conditional fetching
export function useMapboxLocationSuggestions(
  inputValue: string | null | undefined
) {
  const sessionId = useSessionId();

  // Conditional SWR key - null disables fetching
  const { data, error, isLoading } = useSWR<MapboxSuggestResponse>(
    // Key is null (no fetch) unless all conditions met
    sessionId &&
    process.env.NEXT_PUBLIC_MAPBOX_API_KEY &&
    isValidSearchQuery(inputValue)
      ? `https://api.mapbox.com/search/searchbox/v1/suggest?q=${encodeURIComponent(inputValue!)}&session_token=${sessionId}&access_token=${process.env.NEXT_PUBLIC_MAPBOX_API_KEY}`
      : null
  );

  // Transform data with useMemo for performance
  const mappedData = useMemo(() => {
    if (!data) return undefined;

    return data.suggestions
      .filter(isUsState)
      .map(formatMapboxLocation);
  }, [data]);

  return {
    data: mappedData,
    error,
    isLoading
  };
}

// Pure helper functions (outside component/hook)
const isValidSearchQuery = (
  value: string | null | undefined
): value is string => {
  return typeof value === 'string' && value.trim().length >= 2;
};

const isUsState = (suggestion: MapboxSuggestion): boolean => {
  return suggestion.context?.country?.country_code === 'us';
};

const formatMapboxLocation = (
  suggestion: MapboxSuggestion
): LocationSuggestion => ({
  id: suggestion.mapbox_id,
  displayName: suggestion.name,
  region: 'US',
});

Why This Works

Conditional Fetching:

  • SWR doesn't fetch when key is null
  • All conditions checked before constructing URL
  • Type guard isValidSearchQuery ensures type safety
  • Prevents unnecessary API calls on empty input

Data Transformation:

  • useMemo prevents recomputation on every render
  • Dependency array [data] only recomputes when data changes
  • Filter and map operations are pure and testable

Testability:

  • Pure functions can be tested independently
  • No React context needed for helper functions
  • Type guards provide runtime validation

Common Triggers

Use this pattern when:

  • "fetch data based on user input"
  • "conditional API calls with SWR"
  • "transform API response data"
  • "prevent fetching on empty search"
  • "type-safe data fetching hooks"

Pattern 2: Debounced Search with Dual Loading States

The Pattern

Combine debounced input with SWR fetching, tracking both debouncing and network loading states.

typescript
import { useState } from 'react';
import useSWR from 'swr';

// Debounce hook
function useDebounce<T>(value: T, delay: number): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debouncedValue;
}

// Search component with dual loading states
export function SearchComponent() {
  const [searchInput, setSearchInput] = useState('');
  const debouncedSearchInput = useDebounce(searchInput, 300);

  // Track if we're still debouncing (user is typing)
  const isDebouncing = searchInput !== debouncedSearchInput;

  // Fetch with debounced value
  const { data = [], isLoading } = useLocationSuggestions(debouncedSearchInput);

  // Combined loading state: debouncing OR fetching
  const suggestionsLoading = isDebouncing || isLoading;

  return (
    <SearchInput
      value={searchInput}
      onChange={setSearchInput}
      loading={suggestionsLoading}
      suggestions={data}
      placeholder="Search locations..."
    />
  );
}

Why This Works

Dual Loading States:

  • isDebouncing: Indicates user is still typing
  • isLoading: Indicates network request in progress
  • Combined state provides smooth UX feedback

Performance:

  • API calls only fire after 300ms of inactivity
  • Reduces unnecessary requests while typing
  • SWR caches results for instant display

User Experience:

  • Loading indicator appears immediately on typing
  • Prevents result flashing between debounce intervals
  • Clear feedback during both input and fetch phases

Common Triggers

Use this pattern when:

  • "debounced search with loading state"
  • "prevent too many API calls while typing"
  • "show loading indicator during debounce"
  • "smooth search experience"
  • "combine debounce with data fetching"

Pattern 3: Memoized Context Provider

The Pattern

Create context providers with memoized values to prevent unnecessary re-renders of consumers.

typescript
import { createContext, useContext, useState, useCallback, useMemo, ReactNode } from 'react';

// Context value type
interface LocationContextValue {
  location: UserLocation | null;
  requestPreciseLocation: () => Promise<UserLocation | null>;
}

interface UserLocation {
  latitude: number;
  longitude: number;
  accuracy: 'coarse' | 'precise';
}

// Create context with undefined default
const UserLocationContext = createContext<LocationContextValue | undefined>(
  undefined
);

// Provider component
export const UserLocationProvider = ({
  location: initialLocation = null,
  children
}: {
  location?: UserLocation | null;
  children: ReactNode;
}) => {
  const [preciseLocation, setPreciseLocation] = useState<UserLocation | null>(null);

  // Stable callback reference with useCallback
  const requestPreciseLocation = useCallback(async () => {
    try {
      const coords = await getUserCoordinates();
      const location = coords
        ? {
            latitude: coords.latitude,
            longitude: coords.longitude,
            accuracy: 'precise' as const
          }
        : null;

      setPreciseLocation(location);
      return location;
    } catch (error) {
      console.error('Failed to get precise location:', error);
      return null;
    }
  }, []); // No dependencies - function is stable

  // Memoized context value prevents unnecessary re-renders
  const contextValue = useMemo<LocationContextValue>(() => ({
    location: preciseLocation || initialLocation,
    requestPreciseLocation,
  }), [initialLocation, preciseLocation, requestPreciseLocation]);

  return (
    <UserLocationContext.Provider value={contextValue}>
      {children}
    </UserLocationContext.Provider>
  );
};

// Type-safe hook for consuming context
export const useUserLocation = (): LocationContextValue => {
  const context = useContext(UserLocationContext);

  if (context === undefined) {
    throw new Error('useUserLocation must be used within UserLocationProvider');
  }

  return context;
};

// Helper function (can be in separate file)
async function getUserCoordinates(): Promise<GeolocationCoordinates | null> {
  return new Promise((resolve) => {
    navigator.geolocation.getCurrentPosition(
      (position) => resolve(position.coords),
      () => resolve(null),
      { enableHighAccuracy: true }
    );
  });
}

Why This Works

Memoization Prevents Re-renders:

  • useMemo for context value object
  • Only recreates when dependencies change
  • Consumers only re-render when values actually change

Stable References:

  • useCallback ensures requestPreciseLocation reference is stable
  • No dependencies means function never changes
  • Internal state updates don't recreate function

Type Safety:

  • Context hook throws if used outside provider
  • TypeScript enforces correct usage
  • Clear error messages for misuse

Best Practices:

  • Context value is an object with multiple properties
  • Provider manages both props and internal state
  • Custom hook abstracts context consumption

Common Triggers

Use this pattern when:

  • "context causing too many re-renders"
  • "optimize context provider performance"
  • "stable callback in context"
  • "memoized context value"
  • "prevent unnecessary renders from context"

Pattern 4: State Machine for UI States

The Pattern

Use discriminated unions and state machines for predictable UI state management.

typescript
import { useState } from 'react';

// Discriminated union for request states
type RequestState = 'idle' | 'pending' | 'success' | 'error';

// State-specific configuration
const stateConfig: Record<RequestState, {
  label: string;
  disabled: boolean;
  variant: 'primary' | 'success' | 'danger';
}> = {
  idle: {
    label: 'Click to start',
    disabled: false,
    variant: 'primary',
  },
  pending: {
    label: 'Loading...',
    disabled: true,
    variant: 'primary',
  },
  success: {
    label: 'Complete!',
    disabled: false,
    variant: 'success',
  },
  error: {
    label: 'Failed - try again',
    disabled: false,
    variant: 'danger',
  },
};

// Component using state machine
export function AsyncButton({
  onClick
}: {
  onClick: () => Promise<void>;
}) {
  const [state, setState] = useState<RequestState>('idle');

  const handleClick = async () => {
    // State transition: idle/error → pending
    setState('pending');

    try {
      await onClick();
      // State transition: pending → success
      setState('success');

      // Auto-reset after 2 seconds
      setTimeout(() => setState('idle'), 2000);
    } catch (error) {
      // State transition: pending → error
      setState('error');
    }
  };

  const config = stateConfig[state];

  return (
    <button
      onClick={handleClick}
      disabled={config.disabled}
      className={`btn btn-${config.variant}`}
    >
      {config.label}
    </button>
  );
}

Advanced: Tagged Union with Data

For more complex states with state-specific data:

typescript
// Tagged union with discriminated state
type AsyncState<T, E = Error> =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'success'; data: T }
  | { status: 'error'; error: E };

function useAsyncOperation<T>(
  operation: () => Promise<T>
): {
  state: AsyncState<T>;
  execute: () => Promise<void>;
  reset: () => void;
} {
  const [state, setState] = useState<AsyncState<T>>({ status: 'idle' });

  const execute = async () => {
    setState({ status: 'loading' });

    try {
      const data = await operation();
      setState({ status: 'success', data });
    } catch (error) {
      setState({
        status: 'error',
        error: error instanceof Error ? error : new Error('Unknown error')
      });
    }
  };

  const reset = () => {
    setState({ status: 'idle' });
  };

  return { state, execute, reset };
}

// Usage in component
export function DataFetchButton() {
  const { state, execute, reset } = useAsyncOperation(async () => {
    const response = await fetch('/api/data');
    return response.json();
  });

  return (
    <div>
      <button onClick={execute} disabled={state.status === 'loading'}>
        Fetch Data
      </button>

      {state.status === 'loading' && <Spinner />}

      {state.status === 'success' && (
        <div>
          <pre>{JSON.stringify(state.data, null, 2)}</pre>
          <button onClick={reset}>Reset</button>
        </div>
      )}

      {state.status === 'error' && (
        <div className="error">
          {state.error.message}
          <button onClick={reset}>Try Again</button>
        </div>
      )}
    </div>
  );
}

Why This Works

Predictable State Transitions:

  • Explicit states prevent impossible states
  • Clear state transition logic
  • TypeScript ensures all states handled

Type Safety:

  • Discriminated unions enable exhaustive checking
  • State-specific data is type-safe
  • Compiler catches missing state handlers

Maintainability:

  • State configuration in one place
  • Easy to add new states
  • Clear separation of state and UI

Common Triggers

Use this pattern when:

  • "manage async operation states"
  • "predictable UI state machine"
  • "loading, success, error states"
  • "prevent impossible states"
  • "type-safe state management"

Advanced Composition: Combining Patterns

Complete Search Component

Combining debounced search, SWR fetching, and state machine:

typescript
import { useState, useMemo } from 'react';
import useSWR from 'swr';

type SearchState = 'idle' | 'debouncing' | 'fetching' | 'success' | 'error';

export function AdvancedSearch() {
  const [searchInput, setSearchInput] = useState('');
  const debouncedInput = useDebounce(searchInput, 300);

  // Determine current state
  const isDebouncing = searchInput !== debouncedInput;

  // Conditional SWR fetching
  const { data, error, isLoading } = useSWR(
    debouncedInput.length >= 2
      ? `/api/search?q=${encodeURIComponent(debouncedInput)}`
      : null
  );

  // Compute search state
  const searchState = useMemo<SearchState>(() => {
    if (error) return 'error';
    if (isDebouncing) return 'debouncing';
    if (isLoading) return 'fetching';
    if (data) return 'success';
    return 'idle';
  }, [isDebouncing, isLoading, data, error]);

  // State-specific UI
  const showSpinner = searchState === 'debouncing' || searchState === 'fetching';
  const showResults = searchState === 'success';
  const showError = searchState === 'error';

  return (
    <div>
      <input
        type="text"
        value={searchInput}
        onChange={(e) => setSearchInput(e.target.value)}
        placeholder="Search..."
      />

      {showSpinner && <Spinner />}

      {showResults && (
        <SearchResults results={data.results} />
      )}

      {showError && (
        <ErrorMessage>Failed to fetch results</ErrorMessage>
      )}
    </div>
  );
}

Anti-Patterns to Avoid

❌ Don't: Create New Objects in Render

typescript
// BAD: New object on every render causes unnecessary re-renders
function MyProvider({ children }) {
  const [state, setState] = useState(null);

  return (
    <MyContext.Provider value={{ state, setState }}>
      {children}
    </MyContext.Provider>
  );
}
typescript
// GOOD: Memoize the context value
function MyProvider({ children }) {
  const [state, setState] = useState(null);

  const value = useMemo(() => ({ state, setState }), [state]);

  return (
    <MyContext.Provider value={value}>
      {children}
    </MyContext.Provider>
  );
}

❌ Don't: Forget SWR Conditional Fetching

typescript
// BAD: Fetches even with empty input
function useSearch(query: string) {
  const { data } = useSWR(`/api/search?q=${query}`);
  return data;
}
typescript
// GOOD: Only fetch when query is valid
function useSearch(query: string) {
  const { data } = useSWR(
    query.trim().length >= 2 ? `/api/search?q=${query}` : null
  );
  return data;
}

❌ Don't: Ignore Debounce vs Loading State

typescript
// BAD: Only shows loading during network request
function Search() {
  const [input, setInput] = useState('');
  const debounced = useDebounce(input, 300);
  const { data, isLoading } = useSWR(`/api?q=${debounced}`);

  // Spinner disappears while debouncing!
  return <>{isLoading && <Spinner />}</>;
}
typescript
// GOOD: Show loading during both debounce and fetch
function Search() {
  const [input, setInput] = useState('');
  const debounced = useDebounce(input, 300);
  const { data, isLoading } = useSWR(`/api?q=${debounced}`);

  const isDebouncing = input !== debounced;
  const loading = isDebouncing || isLoading;

  return <>{loading && <Spinner />}</>;
}

❌ Don't: Use String States Without Type Safety

typescript
// BAD: Easy to typo, no autocomplete
function Component() {
  const [status, setStatus] = useState('idel'); // Typo!

  if (status === 'idle') { // Won't match
    return <div>Ready</div>;
  }
}
typescript
// GOOD: Use discriminated union
type Status = 'idle' | 'loading' | 'success' | 'error';

function Component() {
  const [status, setStatus] = useState<Status>('idle');

  if (status === 'idle') { // Type-safe
    return <div>Ready</div>;
  }
}

Best Practices Summary

  1. Conditional SWR Keys: Use null to prevent fetching when conditions aren't met
  2. Memoize Transformations: Use useMemo for expensive data transformations
  3. Stable Callbacks: Use useCallback for functions in context or dependencies
  4. Memoize Context Values: Prevent unnecessary re-renders of context consumers
  5. Dual Loading States: Track both debouncing and network loading separately
  6. Pure Helper Functions: Extract logic outside components for testability
  7. Type-Safe States: Use discriminated unions for state machines
  8. Explicit State Transitions: Make state changes predictable and clear

Related Patterns

See the react-state-machine skill for more advanced state machine patterns with XState. See the react-advanced skill for React 19 platform features and rendering architecture — the React Compiler (which changes when manual memoization is needed), concurrent rendering, Actions, and context-optimization at scale.

References

Tệp đi kèm

Mô hình đọc các tệp này khi cần trong lúc kỹ năng được tải. Các tệp được cung cấp ở dạng có thể đọc và không bao giờ được thực thi.

Câu hỏi thường gặp

Kỹ năng AI React Hooks Composition làm được gì?

Advanced React hooks composition patterns - SWR integration, debounced search, memoized contexts, state machines, and performance optimization

Vì sao nên dùng React Hooks Composition trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. React Hooks Composition là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài React Hooks Composition trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/bobmatnyc/claude-mpm-skills/tree/main/toolchains/javascript/frameworks/react/react-hooks-composition. TypingMind đọc tệp SKILL.md, đóng gói các tệp đi kèm và cài đặt thành một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng React Hooks Composition?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Bạn có thể dùng React Hooks Composition với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng React Hooks Composition với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI React Hooks Composition có miễn phí không?

Có. Kỹ năng này được bobmatnyc phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp cho mô hình các công cụ mới để gọi — mã được chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và tiêu chí của đầu ra tốt. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇