第 56 期 - 剖析 Zustand 源码中的 TS 类型运用与实现原理
logoFRONTALK AI/12月18日 16:32/阅读原文

摘要

文章介绍 Zustand 为轻量的 react 状态管理库,详细解读 store 创建、状态类型相关的源码内容,包括 StateCreator、Mutate 等类型,还涉及中间件实现、createImpl 函数,最后总结 Zustand 的特性并分享开源项目

一、Zustand 状态管理库概述

Zustand 是一个非常轻量的 react 状态管理库,它借力于 react hooks,其源码精简且使用方法简单。

二、store 创建逻辑

1. create 方法

export const create = (<T>(createState: StateCreator<T, [], []> | undefined) => 
    createState? createImpl(createState) : createImpl) as Create;

这一设计可以在需要更高灵活性时,通过获取底层的createImpl函数来实现自定义的状态初始化和扩展,支持如延迟初始化、动态创建、多实例化以及中间件集成等复杂的状态管理需求。

三、重要的类型定义

1. StateCreator 类型

export type StateCreator<
    T,
    Mis extends [StoreMutatorIdentifier, unknown][] = [],
    Mos extends [StoreMutatorIdentifier, unknown][] = [],
    U = T> = ((
        setState: Get<Mutate<StoreApi<T>, Mis>, "setState", never>,
        getState: Get<Mutate<StoreApi<T>, Mis>, "getState", never>,
        store: Mutate<StoreApi<T>, Mis>) => U) & { $$storeMutators?: Mos };

2. SetStateInternal 类型

type SetStateInternal<T> = {
    _(
        partial: T | Partial<T> | { _(state: T): T | Partial<T> }["_"],
        replace?: false
    ): void;
    _(state: T | { _(state: T): T }["_"], replace: true): void;
}["_"];

3. Get 类型

type Get<T, K, F> = K extends keyof T? T[K] : F;

例如在获取用户名字类型时,如果K(这里是"name")存在于TUser类型)中,则返回T[K](即string类型),否则返回默认类型F

4. Mutate 类型

export type Mutate<S, Ms> = number extends Ms["length" & keyof Ms]
   ? S
    : Ms extends []
   ? S
    : Ms extends [[infer Mi, infer Ma],...infer Mrs]
   ? Mutate<StoreMutators<S, Ma>[Mi & StoreMutatorIdentifier], Mrs>
    : never;

四、中间件相关实现

interface StoreMutators<S, A> {
    logging: (state: S, action: A, next: (newState: S) => S) => S;
    timestamp: (state: S, action: A, next: (newState: S) => S) => S;
}

五、createImpl 函数

六、关于内存泄漏问题

七、Zustand 的总结

 

扩展阅读

Made by 捣鼓键盘的小麦 / © 2025 Front Talk 版权所有