or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

decorators.mdhooks.mdindex.mdpreview-system.mdstory-composition.mdstory-store.mdtesting-simulation.md

hooks.mddocs/

0

# Hooks API

1

2

React-like hooks for state management, lifecycle methods, and communication within the Storybook preview environment. These hooks enable interactive stories, custom addon development, and advanced story behavior.

3

4

## Capabilities

5

6

### Story State Hooks

7

8

Core hooks for managing story arguments and global state.

9

10

```typescript { .api }

11

/**

12

* Returns current story args, update function, and reset function

13

* @returns Array containing [args, updateArgs, resetArgs]

14

*/

15

function useArgs<TArgs>(): [

16

TArgs,

17

(newArgs: Partial<TArgs>) => void,

18

(argNames?: (keyof TArgs)[]) => void

19

];

20

21

/**

22

* Returns current global args and update function

23

* @returns Array containing [globals, updateGlobals]

24

*/

25

function useGlobals(): [Args, (newGlobals: Args) => void];

26

27

/**

28

* Returns the current story context with metadata

29

* @returns Complete story context object

30

*/

31

function useStoryContext<TRenderer>(): StoryContext<TRenderer>;

32

33

/**

34

* Retrieves parameter value for the current story

35

* @param parameterKey - Key of the parameter to retrieve

36

* @param defaultValue - Default value if parameter is not found

37

* @returns Parameter value or default

38

*/

39

function useParameter<S>(parameterKey: string, defaultValue?: S): S | undefined;

40

```

41

42

**Usage Examples:**

43

44

```typescript

45

import { useArgs, useGlobals, useParameter } from "@storybook/preview-api";

46

47

export const InteractiveDecorator = (Story, context) => {

48

const [args, updateArgs, resetArgs] = useArgs();

49

const [globals, updateGlobals] = useGlobals();

50

const theme = useParameter('theme', 'light');

51

52

const handleClick = () => {

53

updateArgs({ clicked: true });

54

updateGlobals({ ...globals, lastAction: 'click' });

55

};

56

57

return (

58

<div data-theme={theme}>

59

<button onClick={handleClick}>Update Args</button>

60

<button onClick={() => resetArgs(['clicked'])}>Reset</button>

61

<Story />

62

</div>

63

);

64

};

65

```

66

67

### React-like Hooks

68

69

Standard React hook patterns for component lifecycle and state management.

70

71

```typescript { .api }

72

/**

73

* State management hook similar to React.useState

74

* @param initialState - Initial state value or function returning initial state

75

* @returns Array containing [state, setState]

76

*/

77

function useState<S>(initialState: (() => S) | S): [S, (update: ((prevState: S) => S) | S) => void];

78

79

/**

80

* Side effects hook similar to React.useEffect

81

* @param create - Effect function, can return cleanup function

82

* @param deps - Dependency array for effect re-execution

83

*/

84

function useEffect(create: () => (() => void) | void, deps?: any[]): void;

85

86

/**

87

* Memoization hook similar to React.useMemo

88

* @param nextCreate - Function that returns the memoized value

89

* @param deps - Dependency array for memoization

90

* @returns Memoized value

91

*/

92

function useMemo<T>(nextCreate: () => T, deps?: any[]): T;

93

94

/**

95

* Callback memoization hook similar to React.useCallback

96

* @param callback - Function to memoize

97

* @param deps - Dependency array for memoization

98

* @returns Memoized callback function

99

*/

100

function useCallback<T>(callback: T, deps?: any[]): T;

101

102

/**

103

* Mutable ref object hook similar to React.useRef

104

* @param initialValue - Initial value for the ref

105

* @returns Mutable ref object

106

*/

107

function useRef<T>(initialValue: T): { current: T };

108

109

/**

110

* Reducer pattern hook similar to React.useReducer

111

* @param reducer - Reducer function

112

* @param initialState - Initial state value

113

* @returns Array containing [state, dispatch]

114

*/

115

function useReducer<S, A>(

116

reducer: (state: S, action: A) => S,

117

initialState: S

118

): [S, (action: A) => void];

119

```

120

121

**Usage Examples:**

122

123

```typescript

124

export const StatefulDecorator = (Story, context) => {

125

const [count, setCount] = useState(0);

126

const [data, setData] = useState([]);

127

const timerRef = useRef(null);

128

129

useEffect(() => {

130

timerRef.current = setInterval(() => {

131

setCount(c => c + 1);

132

}, 1000);

133

134

return () => {

135

if (timerRef.current) {

136

clearInterval(timerRef.current);

137

}

138

};

139

}, []);

140

141

const memoizedValue = useMemo(() => {

142

return data.filter(item => item.active).length;

143

}, [data]);

144

145

const handleClick = useCallback(() => {

146

setCount(c => c + 1);

147

}, []);

148

149

return (

150

<div>

151

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

152

<p>Active items: {memoizedValue}</p>

153

<Story />

154

</div>

155

);

156

};

157

```

158

159

### Channel Communication

160

161

Hook for subscribing to Storybook's communication channel events.

162

163

```typescript { .api }

164

/**

165

* Subscribe to Storybook channel events

166

* @param eventMap - Object mapping event names to listener functions

167

* @param deps - Dependency array for re-subscription

168

* @returns Function to emit events

169

*/

170

function useChannel(eventMap: EventMap, deps?: any[]): (eventId: string, ...args: any[]) => void;

171

172

interface EventMap {

173

[eventId: string]: Listener;

174

}

175

176

interface Listener {

177

(...args: any[]): void;

178

}

179

```

180

181

**Usage Examples:**

182

183

```typescript

184

export const ChannelDecorator = (Story, context) => {

185

const [messages, setMessages] = useState([]);

186

187

const emit = useChannel({

188

'custom-event': (data) => {

189

setMessages(prev => [...prev, data]);

190

},

191

'reset-messages': () => {

192

setMessages([]);

193

}

194

}, []);

195

196

return (

197

<div>

198

<button onClick={() => emit('custom-event', { text: 'Hello', timestamp: Date.now() })}>

199

Send Message

200

</button>

201

<ul>

202

{messages.map((msg, i) => (

203

<li key={i}>{msg.text} - {msg.timestamp}</li>

204

))}

205

</ul>

206

<Story />

207

</div>

208

);

209

};

210

```

211

212

### Hook Context Management

213

214

Core infrastructure for hook state and lifecycle management.

215

216

```typescript { .api }

217

/**

218

* Core class managing hook state and lifecycle

219

*/

220

class HooksContext<TRenderer, TArgs = any> {

221

constructor(renderContext: RenderContext<TRenderer>);

222

223

/**

224

* Clean hook state and prepare for next render

225

*/

226

clean(): void;

227

228

/**

229

* Get current render context

230

* @returns Current render context

231

*/

232

getRenderContext(): RenderContext<TRenderer>;

233

234

/**

235

* Set hook state for current render

236

* @param index - Hook index

237

* @param value - Hook state value

238

*/

239

setHookState(index: number, value: any): void;

240

241

/**

242

* Get hook state for current render

243

* @param index - Hook index

244

* @returns Hook state value

245

*/

246

getHookState(index: number): any;

247

248

/**

249

* Reset all hook state

250

*/

251

resetHookState(): void;

252

}

253

254

/**

255

* Decorator applicator with hooks support

256

* @returns Decorator function that manages hook context

257

*/

258

function applyHooks<TRenderer>(): DecoratorFunction<TRenderer>;

259

```

260

261

## Types & Interfaces

262

263

```typescript { .api }

264

interface Args {

265

[key: string]: any;

266

}

267

268

interface StoryContext<TRenderer = any> {

269

id: string;

270

name: string;

271

title: string;

272

parameters: Parameters;

273

args: Args;

274

argTypes: ArgTypes;

275

globals: Args;

276

hooks: HooksContext<TRenderer>;

277

viewMode: 'story' | 'docs';

278

}

279

280

interface RenderContext<TRenderer = any> {

281

id: string;

282

title: string;

283

name: string;

284

storyContext: StoryContext<TRenderer>;

285

renderToDOM: Function;

286

unboundStoryFn: Function;

287

}

288

```