or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.mdmiddleware.mdreact-integration.mdstore-creation.mdutilities.md

store-creation.mddocs/

0

# Store Creation

1

2

Core functionality for creating and managing state stores in both React and vanilla JavaScript environments.

3

4

## Capabilities

5

6

### Create Store (React)

7

8

Creates a React-integrated store with hook-based API that automatically triggers re-renders when subscribed state changes.

9

10

```typescript { .api }

11

/**

12

* Creates a React-integrated store with hooks API

13

* @param initializer - Function that creates the initial state and actions

14

* @returns UseBoundStore that can be called as a hook

15

*/

16

function create<T, Mos extends [StoreMutatorIdentifier, unknown][] = []>(

17

initializer: StateCreator<T, [], Mos>

18

): UseBoundStore<Mutate<StoreApi<T>, Mos>>;

19

20

function create<T>(): <Mos extends [StoreMutatorIdentifier, unknown][] = []>(

21

initializer: StateCreator<T, [], Mos>

22

) => UseBoundStore<Mutate<StoreApi<T>, Mos>>;

23

```

24

25

**Usage Examples:**

26

27

```typescript

28

import { create } from "zustand";

29

30

// Simple counter store

31

interface CounterState {

32

count: number;

33

increment: () => void;

34

decrement: () => void;

35

reset: () => void;

36

}

37

38

const useCounterStore = create<CounterState>((set) => ({

39

count: 0,

40

increment: () => set((state) => ({ count: state.count + 1 })),

41

decrement: () => set((state) => ({ count: state.count - 1 })),

42

reset: () => set({ count: 0 }),

43

}));

44

45

// Using in React component

46

function Counter() {

47

const { count, increment, decrement, reset } = useCounterStore();

48

return (

49

<div>

50

<p>Count: {count}</p>

51

<button onClick={increment}>+</button>

52

<button onClick={decrement}>-</button>

53

<button onClick={reset}>Reset</button>

54

</div>

55

);

56

}

57

58

// Async actions

59

interface UserState {

60

users: User[];

61

loading: boolean;

62

fetchUsers: () => Promise<void>;

63

}

64

65

const useUserStore = create<UserState>((set, get) => ({

66

users: [],

67

loading: false,

68

fetchUsers: async () => {

69

set({ loading: true });

70

try {

71

const response = await fetch('/api/users');

72

const users = await response.json();

73

set({ users, loading: false });

74

} catch (error) {

75

set({ loading: false });

76

}

77

},

78

}));

79

```

80

81

### Create Store (Vanilla)

82

83

Creates a vanilla store that works without React, providing imperative access to state management.

84

85

```typescript { .api }

86

/**

87

* Creates a vanilla store without React integration

88

* @param initializer - Function that creates the initial state and actions

89

* @returns StoreApi with imperative methods

90

*/

91

function createStore<T, Mos extends [StoreMutatorIdentifier, unknown][] = []>(

92

initializer: StateCreator<T, [], Mos>

93

): Mutate<StoreApi<T>, Mos>;

94

95

function createStore<T>(): <Mos extends [StoreMutatorIdentifier, unknown][] = []>(

96

initializer: StateCreator<T, [], Mos>

97

) => Mutate<StoreApi<T>, Mos>;

98

```

99

100

**Usage Examples:**

101

102

```typescript

103

import { createStore } from "zustand/vanilla";

104

105

// Vanilla store creation

106

const store = createStore<CounterState>((set) => ({

107

count: 0,

108

increment: () => set((state) => ({ count: state.count + 1 })),

109

decrement: () => set((state) => ({ count: state.count - 1 })),

110

reset: () => set({ count: 0 }),

111

}));

112

113

// Imperative usage

114

console.log(store.getState().count); // 0

115

store.getState().increment();

116

console.log(store.getState().count); // 1

117

118

// Subscribe to changes

119

const unsubscribe = store.subscribe((state, prevState) => {

120

console.log('Count changed from', prevState.count, 'to', state.count);

121

});

122

123

// Later: unsubscribe()

124

```

125

126

### State Creator Pattern

127

128

The StateCreator type defines the function signature for initializing store state and actions.

129

130

```typescript { .api }

131

/**

132

* Function type for creating store state and actions

133

* @param setState - Function to update store state

134

* @param getState - Function to read current store state

135

* @param store - Full store API for advanced usage

136

* @returns Initial state object with actions

137

*/

138

type StateCreator<

139

T,

140

Mis extends [StoreMutatorIdentifier, unknown][] = [],

141

Mos extends [StoreMutatorIdentifier, unknown][] = [],

142

U = T

143

> = ((

144

setState: Get<Mutate<StoreApi<T>, Mis>, 'setState', never>,

145

getState: Get<Mutate<StoreApi<T>, Mis>, 'getState', never>,

146

store: Mutate<StoreApi<T>, Mis>

147

) => U) & { $$storeMutators?: Mos };

148

```

149

150

**setState Usage:**

151

152

```typescript

153

// Partial updates (recommended)

154

set((state) => ({ count: state.count + 1 }));

155

156

// Object merge updates

157

set({ loading: false });

158

159

// Complete replacement (use carefully)

160

set(newState, true);

161

```

162

163

**getState Usage:**

164

165

```typescript

166

const useStore = create((set, get) => ({

167

count: 0,

168

doubleCount: () => {

169

const currentCount = get().count;

170

set({ count: currentCount * 2 });

171

},

172

getCountPlusOne: () => get().count + 1,

173

}));

174

```

175

176

### Store API Interface

177

178

Core interface provided by all Zustand stores, available in both React and vanilla environments.

179

180

```typescript { .api }

181

/**

182

* Core store interface with state management methods

183

*/

184

interface StoreApi<T> {

185

/** Update store state with partial or complete replacement */

186

setState: SetStateInternal<T>;

187

/** Get current store state */

188

getState: () => T;

189

/** Get initial store state */

190

getInitialState: () => T;

191

/** Subscribe to state changes */

192

subscribe: (listener: (state: T, prevState: T) => void) => () => void;

193

}

194

195

type SetStateInternal<T> = {

196

_(

197

partial: T | Partial<T> | { _(state: T): T | Partial<T> }['_'],

198

replace?: false

199

): void;

200

_(state: T | { _(state: T): T }['_'], replace: true): void;

201

}['_'];

202

```

203

204

### Type Utilities

205

206

Helper types for extracting state and working with store APIs.

207

208

```typescript { .api }

209

/**

210

* Extract state type from store API

211

*/

212

type ExtractState<S> = S extends { getState: () => infer T } ? T : never;

213

214

/**

215

* Utility type for middleware composition

216

*/

217

type Mutate<S, Ms> = number extends Ms['length' & keyof Ms]

218

? S

219

: Ms extends []

220

? S

221

: Ms extends [[infer Mi, infer Ma], ...infer Mrs]

222

? Mutate<StoreMutators<S, Ma>[Mi & StoreMutatorIdentifier], Mrs>

223

: never;

224

225

/**

226

* Base interface for store mutators (extended by middleware)

227

*/

228

interface StoreMutators<S, A> {}

229

type StoreMutatorIdentifier = keyof StoreMutators<unknown, unknown>;

230

```