MCP HubMCP Hub
スキル一覧に戻る

compose-hooks

majiayu000
更新日 Yesterday
19 閲覧
58
9
58
GitHubで表示
その他react

について

ComposeHooksは、Jetpack Compose/Compose Multiplatform向けに、React Hooksスタイルの状態管理と副作用処理を提供します。コンポーネントの状態管理にuseState、useEffect、useReducerなどの使い慣れたフックが必要な場合や、ネットワークリクエスト(useRequest)、デバウンス、タイマー、グローバル状態管理のユーティリティが必要な場合にご利用ください。Composeアプリケーションにおけるリスト、マップ、テーブル、ライフサイクル管理のための包括的なフックを提供します。

クイックインストール

Claude Code

推奨
プラグインコマンド推奨
/plugin add https://github.com/majiayu000/claude-skill-registry
Git クローン代替
git clone https://github.com/majiayu000/claude-skill-registry.git ~/.claude/skills/compose-hooks

このコマンドをClaude Codeにコピー&ペーストしてスキルをインストールします

ドキュメント

ComposeHooks 使用指南

ComposeHooks 是一个为 Jetpack Compose/Compose Multiplatform 设计的 Hooks 库,灵感来自 React Hooks 和 ahooks。

核心概念

所有 useXxx 函数都有对应的 rememberXxx 别名,选择你喜欢的命名风格。

快速参考

状态管理 Hooks

Hook用途示例
useState基础状态管理(推荐用 by 委托)var state by useState("")
useGetState解构使用的状态管理(推荐)val (state, setState, getState) = useGetState(0)
useBoolean布尔状态管理val (state, toggle, setValue, setTrue, setFalse) = useBoolean(false)
useReducerRedux 风格状态管理val (state, dispatch) = useReducer(reducer, initialState)
useRef不触发重组的引用val ref = useRef(0)
useList列表状态管理val list = useList(1, 2, 3)
useMapMap 状态管理val map = useMap("key" to "value")

副作用 Hooks

Hook用途示例
useEffect副作用处理useEffect(dep) { /* effect */ }
useMount组件挂载时执行useMount { loadData() }
useUnmount组件卸载时执行useUnmount { cleanup() }
useUpdateEffect跳过首次执行的 EffectuseUpdateEffect(dep) { /* effect */ }

网络请求

Hook用途示例
useRequest网络请求管理val (data, loading, error, request) = useRequest(requestFn)

工具 Hooks

Hook用途示例
useDebounce防抖值val debouncedValue = useDebounce(value)
useThrottle节流值val throttledValue = useThrottle(value)
useInterval定时器useInterval { tick() }
useTimeoutFn延时执行useTimeoutFn(fn, 1.seconds)
useUndo撤销/重做val (state, set, reset, undo, redo) = useUndo(initial)

详细参考

常见模式

1. 受控组件

// 推荐:使用 useGetState 解构
val (text, setText) = useGetState("")
OutlinedTextField(
    value = text.value,
    onValueChange = setText,
    label = { Text("输入") }
)

// 或使用 by 委托
var text by useState("")
OutlinedTextField(
    value = text,
    onValueChange = { text = it },
    label = { Text("输入") }
)

2. 解决闭包问题(来自 UseStateExample.kt)

// 方式1: 使用 useGetState 函数式更新
val (state, setState) = useGetState("initial")
LaunchedEffect(Unit) {
    repeat(10) {
        delay(1.seconds)
        setState { "$it." }  // 函数式更新,避免闭包问题
    }
}

// 方式2: 使用 by 委托
var byState by useState("initial")
LaunchedEffect(Unit) {
    repeat(10) {
        delay(1.seconds)
        byState += "."  // 直接修改,无闭包问题
    }
}

// 方式3: 使用 useLatestRef
val (state, setState) = useState("initial")
val stateRef = useLatestRef(state)
LaunchedEffect(Unit) {
    repeat(10) {
        delay(1.seconds)
        setState("${stateRef.current}.")  // 通过 ref 获取最新值
    }
}

3. 网络请求(来自 Auto&Manual.kt)

// 自动请求
val (userInfoState, loadingState, errorState) = useRequest(
    requestFn = { NetApi.userInfo(it) },
    optionsOf = {
        defaultParams = "junerver"  // 自动请求必须设置默认参数
    }
)
val userInfo by userInfoState
val loading by loadingState

if (loading) {
    Text(text = "loading ...")
}
userInfo?.let { Text(text = it.toString()) }

// 手动请求
val (repoInfoState, loadingState, errorState, request) = useRequest(
    requestFn = { it: Tuple2<String, String> ->
        NetApi.repoInfo(it.first, it.second)
    },
    optionsOf = {
        manual = true
        defaultParams = tuple("junerver", "ComposeHooks")
    }
)
TButton(text = "request") { request() }

4. Redux 风格状态管理(来自 UseReducerExample.kt)

// 定义 State 和 Action
data class SimpleData(val name: String, val age: Int)

sealed interface SimpleAction {
    data class ChangeName(val newName: String) : SimpleAction
    data object AgeIncrease : SimpleAction
}

// 定义 Reducer
val simpleReducer: Reducer<SimpleData, SimpleAction> = { prevState, action ->
    when (action) {
        is SimpleAction.ChangeName -> prevState.copy(name = action.newName)
        is SimpleAction.AgeIncrease -> prevState.copy(age = prevState.age + 1)
    }
}

// 使用
val (state, dispatch) = useReducer(
    simpleReducer,
    initialState = SimpleData("default", 18),
    middlewares = arrayOf(logMiddleware())
)

TButton(text = "Change Name") { dispatch(SimpleAction.ChangeName("Alice")) }
TButton(text = "Increase Age") { dispatch(SimpleAction.AgeIncrease) }
Text(text = "State: ${state.value}")

5. 列表操作(来自 UseListExample.kt)

val listState = useList(1, 2, 3)

// 操作方法
listState.add(4)              // 添加
listState.add(0, 0)           // 插入
listState.removeAt(0)         // 删除
listState.removeLast()        // 删除最后一个
listState[0] = 10             // 修改
listState.clear()             // 清空
listState.shuffle()           // 打乱

// 配合 useListReduce
val sum by useListReduce(listState) { a, b -> a + b }

6. 防抖输入(来自 UseDebounceExample.kt)

var inputValue by useState("")
val debouncedValue by useDebounce(
    value = inputValue,
    optionsOf = {
        wait = 500.milliseconds
    }
)

OutlinedTextField(
    value = inputValue,
    onValueChange = { inputValue = it },
    label = { Text("Type something...") }
)

Text(text = "Debounced: $debouncedValue")

GitHub リポジトリ

majiayu000/claude-skill-registry
パス: skills/compose-hooks

関連スキル

content-collections

メタ

This skill provides a production-tested setup for Content Collections, a TypeScript-first tool that transforms Markdown/MDX files into type-safe data collections with Zod validation. Use it when building blogs, documentation sites, or content-heavy Vite + React applications to ensure type safety and automatic content validation. It covers everything from Vite plugin configuration and MDX compilation to deployment optimization and schema validation.

スキルを見る

cloudflare-turnstile

メタ

This skill provides comprehensive guidance for implementing Cloudflare Turnstile as a CAPTCHA-alternative bot protection system. It covers integration for forms, login pages, API endpoints, and frameworks like React/Next.js/Hono, while handling invisible challenges that maintain user experience. Use it when migrating from reCAPTCHA, debugging error codes, or implementing token validation and E2E tests.

スキルを見る

langchain

メタ

LangChain is a framework for building LLM applications using agents, chains, and RAG pipelines. It supports multiple LLM providers, offers 500+ integrations, and includes features like tool calling and memory management. Use it for rapid prototyping and deploying production systems like chatbots, autonomous agents, and question-answering services.

スキルを見る

clerk-auth

メタ

This skill provides comprehensive guidance for implementing Clerk authentication across React, Next.js, and Cloudflare Workers applications. Use it when setting up protected routes, configuring JWT templates with custom claims, integrating with UI components, or testing authentication flows. It also helps prevent common issues like missing secret keys, JWT size limits, and middleware configuration errors.

スキルを見る