or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

content-manager.mdfeatures.mdhooks.mdindex.mdtypes.mdui-components.mdutilities.md

hooks.mddocs/

0

# Hooks

1

2

The @strapi/helper-plugin package provides 15 React hooks that encapsulate common plugin functionality including API communication, state management, permissions checking, and user interactions. These hooks follow React best practices and provide consistent interfaces for plugin development.

3

4

## API & HTTP Client Hooks

5

6

Hooks for making HTTP requests and handling API communication with authentication and error handling.

7

8

```typescript { .api }

9

// HTTP client hook with abort signal support

10

interface FetchClientReturn {

11

get: <TData = any>(url: string, config?: any) => Promise<TData>;

12

post: <TData = any, TResponse = any>(url: string, data?: any, config?: any) => Promise<TResponse>;

13

put: <TData = any>(url: string, data?: any, config?: any) => Promise<TData>;

14

del: <TData = any>(url: string, config?: any) => Promise<TData>;

15

}

16

function useFetchClient(): FetchClientReturn;

17

18

// API error handler hook

19

interface APIErrorHandlerReturn {

20

(error: any): void;

21

}

22

function useAPIErrorHandler(formatMessage?: (descriptor: any) => string): APIErrorHandlerReturn;

23

```

24

25

**Usage Examples:**

26

27

```typescript

28

// HTTP client with automatic abort on unmount

29

const { get, post, put, del } = useFetchClient();

30

31

const fetchArticles = async () => {

32

const response = await get('/api/articles');

33

return response;

34

};

35

36

// API error handling

37

const handleAPIError = useAPIErrorHandler();

38

39

const saveArticle = async (data) => {

40

try {

41

await post('/api/articles', data);

42

} catch (error) {

43

handleAPIError(error);

44

}

45

};

46

```

47

48

## Permission & RBAC Hooks

49

50

Hooks for managing role-based access control and checking user permissions.

51

52

```typescript { .api }

53

// Role-based access control hook

54

interface Permission {

55

action: string;

56

subject: string;

57

conditions?: any[];

58

}

59

60

interface AllowedActions {

61

[key: string]: boolean;

62

}

63

64

interface RBACReturn {

65

allowedActions: AllowedActions;

66

isLoading: boolean;

67

setIsLoading: () => void;

68

}

69

70

function useRBAC(

71

permissionsToCheck?: Record<string, Permission[]>,

72

passedPermissions?: Permission[]

73

): RBACReturn;

74

```

75

76

**Usage Examples:**

77

78

```typescript

79

// Check permissions for multiple actions

80

const { allowedActions, isLoading } = useRBAC({

81

create: [{ action: 'create', subject: 'plugin::my-plugin.entity' }],

82

read: [{ action: 'read', subject: 'plugin::my-plugin.entity' }],

83

update: [{ action: 'update', subject: 'plugin::my-plugin.entity' }],

84

delete: [{ action: 'delete', subject: 'plugin::my-plugin.entity' }]

85

});

86

87

// Use the permissions

88

if (allowedActions.canCreate) {

89

// Show create button

90

}

91

```

92

93

## State Management Hooks

94

95

Hooks for managing component state, selections, and persistent data.

96

97

```typescript { .api }

98

// Selection state management hook

99

interface SelectionActions<TValues> {

100

selectOne: (selection: TValues) => void;

101

selectAll: (nextSelections: TValues[]) => void;

102

selectOnly: (nextSelection: TValues) => void;

103

selectMultiple: (nextSelections: TValues[]) => void;

104

deselectMultiple: (nextSelections: TValues[]) => void;

105

setSelections: (selections: TValues[]) => void;

106

}

107

108

function useSelectionState<TValues extends object>(

109

keys: Array<keyof TValues>,

110

initialValue: TValues[]

111

): readonly [TValues[], SelectionActions<TValues>];

112

113

// Persistent state hook with localStorage

114

function usePersistentState<T>(

115

key: string,

116

initialValue: T

117

): readonly [T, (value: T | ((prev: T) => T)) => void];

118

119

// Callback ref hook

120

function useCallbackRef<T extends HTMLElement>(

121

callback: (element: T | null) => void

122

): React.RefCallback<T>;

123

```

124

125

**Usage Examples:**

126

127

```typescript

128

// Multiple selection management

129

const [selections, { selectOne, selectAll, deselectMultiple }] = useSelectionState(

130

['id'],

131

[]

132

);

133

134

// Persistent state across sessions

135

const [preferences, setPreferences] = usePersistentState('plugin-preferences', {

136

theme: 'light',

137

language: 'en'

138

});

139

140

// Callback ref for element access

141

const elementRef = useCallbackRef<HTMLDivElement>((element) => {

142

if (element) {

143

element.focus();

144

}

145

});

146

```

147

148

## URL & Query Parameter Hooks

149

150

Hooks for managing URL state and query parameters with browser history integration.

151

152

```typescript { .api }

153

// Query parameter management hook

154

interface QueryResult<TQuery> {

155

query: TQuery;

156

rawQuery: string;

157

}

158

159

function useQueryParams<TQuery extends object>(

160

initialParams?: TQuery

161

): readonly [

162

QueryResult<TQuery>,

163

(nextParams: TQuery, method?: 'push' | 'remove') => void

164

];

165

166

// Simple query hook for URL parameters

167

function useQuery(): URLSearchParams;

168

```

169

170

**Usage Examples:**

171

172

```typescript

173

// Manage complex query parameters

174

const [{ query }, setQuery] = useQueryParams({

175

page: 1,

176

pageSize: 20,

177

sort: 'name:asc'

178

});

179

180

// Update URL parameters

181

const handlePageChange = (page: number) => {

182

setQuery({ ...query, page });

183

};

184

185

// Remove parameters

186

const clearFilters = () => {

187

setQuery({ filters: undefined }, 'remove');

188

};

189

190

// Simple query access

191

const searchParams = useQuery();

192

const searchTerm = searchParams.get('search');

193

```

194

195

## Data Filtering & Processing

196

197

Hooks for filtering, collating, and processing data.

198

199

```typescript { .api }

200

// Data filtering hook

201

interface FilterReturn<TData> {

202

filteredData: TData[];

203

filters: Record<string, any>;

204

setFilters: (filters: Record<string, any>) => void;

205

resetFilters: () => void;

206

}

207

208

function useFilter<TData>(

209

data: TData[],

210

initialFilters?: Record<string, any>

211

): FilterReturn<TData>;

212

213

// Internationalized string collation hook

214

interface CollatorOptions extends Intl.CollatorOptions {

215

locale?: string;

216

}

217

218

function useCollator(

219

locale?: string,

220

options?: CollatorOptions

221

): Intl.Collator;

222

```

223

224

**Usage Examples:**

225

226

```typescript

227

// Filter data with multiple criteria

228

const { filteredData, filters, setFilters } = useFilter(articles, {

229

status: 'published'

230

});

231

232

const handleStatusFilter = (status: string) => {

233

setFilters({ ...filters, status });

234

};

235

236

// Internationalized string comparison

237

const collator = useCollator('en', {

238

numeric: true,

239

sensitivity: 'base'

240

});

241

242

const sortedItems = items.sort((a, b) =>

243

collator.compare(a.name, b.name)

244

);

245

```

246

247

## UI Interaction Hooks

248

249

Hooks for managing UI interactions, focus, and user interface behaviors.

250

251

```typescript { .api }

252

// Input field focus management hook

253

function useFocusInputField(shouldFocus?: boolean): React.RefObject<HTMLInputElement>;

254

255

// Focus management on navigation hook

256

function useFocusWhenNavigate(): React.RefObject<HTMLElement>;

257

258

// Scroll locking hook for modals/overlays

259

function useLockScroll(shouldLock?: boolean): void;

260

261

// Clipboard operations hook

262

interface ClipboardReturn {

263

copy: (value: string | number) => Promise<boolean>;

264

}

265

266

function useClipboard(): ClipboardReturn;

267

```

268

269

**Usage Examples:**

270

271

```typescript

272

// Auto-focus input field

273

const inputRef = useFocusInputField(isModalOpen);

274

275

<input ref={inputRef} />

276

277

// Focus on navigation

278

const mainRef = useFocusWhenNavigate();

279

280

<main ref={mainRef}>

281

{/* Content */}

282

</main>

283

284

// Lock scroll when modal is open

285

useLockScroll(isModalOpen);

286

287

// Clipboard functionality

288

const { copy } = useClipboard();

289

290

const handleCopy = async () => {

291

const success = await copy(textToCopy);

292

if (success) {

293

showNotification('Copied to clipboard');

294

}

295

};

296

```

297

298

## Implementation Notes

299

300

### useFetchClient

301

302

- Automatically handles request cancellation on component unmount

303

- Returns a configured axios instance with authentication headers

304

- Supports all HTTP methods with TypeScript generics for response types

305

306

### useRBAC

307

308

- Checks permissions against the user's current roles and permissions

309

- Supports conditional permissions that require API validation

310

- Returns loading state during permission checks

311

- Automatically prefixes action names with "can" in the returned object

312

313

### useSelectionState

314

315

- Generic hook that works with any object type

316

- Uses provided keys to determine item equality

317

- Supports single, multiple, and bulk selection operations

318

- Immutable state updates for optimal React performance

319

320

### useQueryParams

321

322

- Integrates with React Router for browser history management

323

- Supports typed query parameters with TypeScript generics

324

- Handles parameter encoding/decoding automatically

325

- Supports both adding and removing parameters

326

327

### Performance Considerations

328

329

- All hooks use React.useMemo and React.useCallback for optimization

330

- useRBAC uses React Query for permission caching

331

- usePersistentState debounces localStorage writes

332

- useCollator caches collator instances for performance

333

334

### Error Handling

335

336

- useFetchClient automatically cancels requests on unmount

337

- useAPIErrorHandler provides consistent error message formatting

338

- useClipboard gracefully handles clipboard API failures

339

- All hooks include proper cleanup in useEffect return functions