@foundrykit/hooks 2.0.6 → 2.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @foundrykit/hooks
2
2
 
3
+ ## 2.0.8
4
+
5
+ ### Patch Changes
6
+
7
+ - [#132](https://github.com/umi-labs/foundry/pull/132) [`c53bf3e`](https://github.com/umi-labs/foundry/commit/c53bf3e9bad2af8d9011932452fe3d435c9d3cab) Thanks [@sneddonisaac](https://github.com/sneddonisaac)! - `useLocalStorage` no longer causes hydration mismatches: it renders `initialValue` on the server and on the first client render, then reads the stored value in an effect. The built bundle keeps `'use client'` (tsup banner), so the module-level `createContext` calls no longer break Server Component imports. `react`/`react-dom` are peer dependencies only. `sideEffects: false`, and `verify:pack` runs publint and attw.
8
+
9
+ ## 2.0.7
10
+
11
+ ### Patch Changes
12
+
13
+ - [#43](https://github.com/umi-labs/foundry/pull/43) [`b6fc94d`](https://github.com/umi-labs/foundry/commit/b6fc94d3b0f172aa309388f61bd5306af6405fdf) Thanks [@sneddonisaac](https://github.com/sneddonisaac)! - Package metadata now points at the `umi-labs/foundry` monorepo, and releases publish through npm trusted publishing.
14
+
3
15
  ## 2.0.6
4
16
 
5
17
  ### Patch Changes
package/README.md CHANGED
@@ -1,16 +1,8 @@
1
1
  # @foundrykit/hooks
2
2
 
3
- A collection of custom React hooks for common UI patterns and functionality.
4
- Provides reusable logic for state management, user interactions, and component
5
- behaviour.
6
-
7
- ## Features
8
-
9
- - **Custom hooks** - Reusable logic for common UI patterns
10
- - **TypeScript support** - Full type safety with comprehensive definitions
11
- - **Performance optimized** - Efficient implementations with proper cleanup
12
- - **Accessibility focused** - Hooks that support accessibility best practices
13
- - **Framework agnostic** - Works with any React setup
3
+ A collection of custom React hooks for common UI patterns used across the
4
+ FoundryKit ecosystem — debouncing, persisted state, media queries, click
5
+ handling, form fields, and advanced search.
14
6
 
15
7
  ## Installation
16
8
 
@@ -18,448 +10,46 @@ behaviour.
18
10
  pnpm add @foundrykit/hooks
19
11
  ```
20
12
 
21
- ## Available Hooks
22
-
23
- ### State Management
24
-
25
- - **useLocalStorage** - Persist state in localStorage
26
- - **useDebouncedValue** - Debounce values for performance
27
- - **useMediaQuery** - React to media query changes
28
- - **useClickOutside** - Detect clicks outside elements
29
-
30
- ### Form Hooks
31
-
32
- - **useForm** - Form state management
33
- - **useField** - Individual field management
34
- - **useValidation** - Form validation logic
35
-
36
- ### UI Hooks
37
-
38
- - **useDialog** - Dialog/modal state management
39
- - **usePopover** - Popover positioning and state
40
- - **useTooltip** - Tooltip positioning and visibility
41
-
42
- ### Utility Hooks
43
-
44
- - **usePrevious** - Access previous value
45
- - **useInterval** - Set up intervals with cleanup
46
- - **useTimeout** - Set up timeouts with cleanup
47
-
48
13
  ## Usage
49
14
 
50
- ### State Management Hooks
51
-
52
- #### useLocalStorage
53
-
54
- Persist state in localStorage with automatic serialization:
55
-
56
- ```tsx
57
- import { useLocalStorage } from '@foundrykit/hooks';
58
-
59
- function UserPreferences() {
60
- const [theme, setTheme] = useLocalStorage('theme', 'light');
61
- const [language, setLanguage] = useLocalStorage('language', 'en');
62
-
63
- return (
64
- <div>
65
- <select value={theme} onChange={e => setTheme(e.target.value)}>
66
- <option value='light'>Light</option>
67
- <option value='dark'>Dark</option>
68
- </select>
69
-
70
- <select value={language} onChange={e => setLanguage(e.target.value)}>
71
- <option value='en'>English</option>
72
- <option value='es'>Spanish</option>
73
- </select>
74
- </div>
75
- );
76
- }
77
- ```
78
-
79
- #### useDebouncedValue
80
-
81
- Debounce values to improve performance:
82
-
83
15
  ```tsx
84
- import { useDebouncedValue } from '@foundrykit/hooks';
16
+ import { useDebouncedValue, useIsMobile } from '@foundrykit/hooks';
85
17
 
86
- function SearchComponent() {
18
+ function Search() {
87
19
  const [query, setQuery] = useState('');
88
20
  const debouncedQuery = useDebouncedValue(query, 300);
89
-
90
- // This effect only runs when debouncedQuery changes
91
- useEffect(() => {
92
- if (debouncedQuery) {
93
- searchAPI(debouncedQuery);
94
- }
95
- }, [debouncedQuery]);
21
+ const isMobile = useIsMobile();
96
22
 
97
23
  return (
98
24
  <input
99
25
  value={query}
100
26
  onChange={e => setQuery(e.target.value)}
101
- placeholder='Search...'
27
+ placeholder={isMobile ? 'Search' : 'Search the catalog...'}
102
28
  />
103
29
  );
104
30
  }
105
31
  ```
106
32
 
107
- #### useMediaQuery
108
-
109
- React to media query changes:
110
-
111
- ```tsx
112
- import { useMediaQuery } from '@foundrykit/hooks';
113
-
114
- function ResponsiveComponent() {
115
- const isMobile = useMediaQuery('(max-width: 768px)');
116
- const isTablet = useMediaQuery('(min-width: 769px) and (max-width: 1024px)');
117
- const isDesktop = useMediaQuery('(min-width: 1025px)');
118
-
119
- return (
120
- <div>
121
- {isMobile && <MobileLayout />}
122
- {isTablet && <TabletLayout />}
123
- {isDesktop && <DesktopLayout />}
124
- </div>
125
- );
126
- }
127
- ```
128
-
129
- ### UI Interaction Hooks
130
-
131
- #### useClickOutside
132
-
133
- Detect clicks outside an element:
134
-
135
- ```tsx
136
- import { useClickOutside } from '@foundrykit/hooks';
137
-
138
- function Dropdown({ isOpen, onClose, children }) {
139
- const ref = useRef(null);
140
-
141
- useClickOutside(ref, () => {
142
- if (isOpen) {
143
- onClose();
144
- }
145
- });
146
-
147
- if (!isOpen) return null;
148
-
149
- return (
150
- <div ref={ref} className='dropdown'>
151
- {children}
152
- </div>
153
- );
154
- }
155
- ```
156
-
157
- #### useDialog
158
-
159
- Manage dialog/modal state:
160
-
161
- ```tsx
162
- import { useDialog } from '@foundrykit/hooks';
163
-
164
- function ModalExample() {
165
- const { isOpen, open, close, toggle } = useDialog();
166
-
167
- return (
168
- <div>
169
- <button onClick={open}>Open Modal</button>
170
-
171
- {isOpen && (
172
- <div className='modal-overlay' onClick={close}>
173
- <div className='modal-content' onClick={e => e.stopPropagation()}>
174
- <h2>Modal Content</h2>
175
- <button onClick={close}>Close</button>
176
- </div>
177
- </div>
178
- )}
179
- </div>
180
- );
181
- }
182
- ```
183
-
184
- ### Form Hooks
185
-
186
- #### useForm
187
-
188
- Complete form state management:
189
-
190
- ```tsx
191
- import { useForm } from '@foundrykit/hooks';
192
-
193
- function ContactForm() {
194
- const {
195
- values,
196
- errors,
197
- touched,
198
- handleChange,
199
- handleBlur,
200
- handleSubmit,
201
- isSubmitting,
202
- } = useForm({
203
- initialValues: {
204
- name: '',
205
- email: '',
206
- message: '',
207
- },
208
- validate: values => {
209
- const errors = {};
210
- if (!values.name) errors.name = 'Name is required';
211
- if (!values.email) errors.email = 'Email is required';
212
- if (!values.message) errors.message = 'Message is required';
213
- return errors;
214
- },
215
- onSubmit: async values => {
216
- await submitForm(values);
217
- },
218
- });
219
-
220
- return (
221
- <form onSubmit={handleSubmit}>
222
- <input
223
- name='name'
224
- value={values.name}
225
- onChange={handleChange}
226
- onBlur={handleBlur}
227
- className={touched.name && errors.name ? 'error' : ''}
228
- />
229
- {touched.name && errors.name && <span>{errors.name}</span>}
230
-
231
- <input
232
- name='email'
233
- value={values.email}
234
- onChange={handleChange}
235
- onBlur={handleBlur}
236
- className={touched.email && errors.email ? 'error' : ''}
237
- />
238
- {touched.email && errors.email && <span>{errors.email}</span>}
239
-
240
- <textarea
241
- name='message'
242
- value={values.message}
243
- onChange={handleChange}
244
- onBlur={handleBlur}
245
- className={touched.message && errors.message ? 'error' : ''}
246
- />
247
- {touched.message && errors.message && <span>{errors.message}</span>}
248
-
249
- <button type='submit' disabled={isSubmitting}>
250
- {isSubmitting ? 'Sending...' : 'Send Message'}
251
- </button>
252
- </form>
253
- );
254
- }
255
- ```
256
-
257
- ### Utility Hooks
258
-
259
- #### usePrevious
260
-
261
- Access the previous value:
262
-
263
- ```tsx
264
- import { usePrevious } from '@foundrykit/hooks';
265
-
266
- function Counter() {
267
- const [count, setCount] = useState(0);
268
- const previousCount = usePrevious(count);
269
-
270
- return (
271
- <div>
272
- <p>Current: {count}</p>
273
- <p>Previous: {previousCount}</p>
274
- <button onClick={() => setCount(count + 1)}>Increment</button>
275
- </div>
276
- );
277
- }
278
- ```
279
-
280
- #### useInterval
281
-
282
- Set up intervals with automatic cleanup:
283
-
284
- ```tsx
285
- import { useInterval } from '@foundrykit/hooks';
286
-
287
- function Timer() {
288
- const [seconds, setSeconds] = useState(0);
289
- const [isRunning, setIsRunning] = useState(false);
290
-
291
- useInterval(() => setSeconds(seconds + 1), isRunning ? 1000 : null);
292
-
293
- return (
294
- <div>
295
- <p>Seconds: {seconds}</p>
296
- <button onClick={() => setIsRunning(!isRunning)}>
297
- {isRunning ? 'Pause' : 'Start'}
298
- </button>
299
- </div>
300
- );
301
- }
302
- ```
303
-
304
- ## Advanced Usage
305
-
306
- ### Custom Hook Composition
307
-
308
- Combine multiple hooks for complex functionality:
309
-
310
- ```tsx
311
- import {
312
- useLocalStorage,
313
- useDebouncedValue,
314
- useMediaQuery,
315
- } from '@foundrykit/hooks';
316
-
317
- function useResponsiveSearch() {
318
- const [query, setQuery] = useLocalStorage('search-query', '');
319
- const debouncedQuery = useDebouncedValue(query, 300);
320
- const isMobile = useMediaQuery('(max-width: 768px)');
321
-
322
- const searchResults = useMemo(() => {
323
- if (!debouncedQuery) return [];
324
- return performSearch(debouncedQuery, { limit: isMobile ? 5 : 10 });
325
- }, [debouncedQuery, isMobile]);
326
-
327
- return {
328
- query,
329
- setQuery,
330
- debouncedQuery,
331
- searchResults,
332
- isMobile,
333
- };
334
- }
335
- ```
336
-
337
- ### Hook with Dependencies
338
-
339
- ```tsx
340
- import { useClickOutside } from '@foundrykit/hooks';
341
-
342
- function useDropdown(initialState = false) {
343
- const [isOpen, setIsOpen] = useState(initialState);
344
- const ref = useRef(null);
345
-
346
- useClickOutside(ref, () => setIsOpen(false));
347
-
348
- const open = useCallback(() => setIsOpen(true), []);
349
- const close = useCallback(() => setIsOpen(false), []);
350
- const toggle = useCallback(() => setIsOpen(!isOpen), [isOpen]);
351
-
352
- return {
353
- isOpen,
354
- ref,
355
- open,
356
- close,
357
- toggle,
358
- };
359
- }
360
- ```
361
-
362
- ### Performance Optimization
363
-
364
- ```tsx
365
- import { useDebouncedValue } from '@foundrykit/hooks';
366
-
367
- function OptimizedSearch() {
368
- const [query, setQuery] = useState('');
369
- const debouncedQuery = useDebouncedValue(query, 500);
370
-
371
- // Memoize expensive operation
372
- const searchResults = useMemo(() => {
373
- if (!debouncedQuery) return [];
374
- return expensiveSearch(debouncedQuery);
375
- }, [debouncedQuery]);
376
-
377
- return (
378
- <div>
379
- <input
380
- value={query}
381
- onChange={e => setQuery(e.target.value)}
382
- placeholder='Search...'
383
- />
384
- <SearchResults results={searchResults} />
385
- </div>
386
- );
387
- }
388
- ```
389
-
390
- ## TypeScript Support
391
-
392
- All hooks include comprehensive TypeScript definitions:
393
-
394
- ```tsx
395
- import { useLocalStorage, useDebouncedValue } from '@foundrykit/hooks';
396
-
397
- // Type-safe localStorage hook
398
- const [user, setUser] = useLocalStorage<User>('user', null);
399
-
400
- // Type-safe debounced value
401
- const [searchTerm, setSearchTerm] = useState<string>('');
402
- const debouncedSearchTerm = useDebouncedValue<string>(searchTerm, 300);
403
- ```
404
-
405
- ## Best Practices
406
-
407
- ### Hook Dependencies
408
-
409
- ```tsx
410
- // ✅ Good - Stable callback
411
- const handleClick = useCallback(() => {
412
- console.log('clicked');
413
- }, []);
414
-
415
- // ❌ Avoid - Unstable callback
416
- const handleClick = () => {
417
- console.log('clicked');
418
- };
419
- ```
420
-
421
- ### Cleanup
422
-
423
- ```tsx
424
- // ✅ Good - Proper cleanup
425
- useEffect(() => {
426
- const timer = setTimeout(() => {
427
- // do something
428
- }, 1000);
429
-
430
- return () => clearTimeout(timer);
431
- }, []);
432
-
433
- // ❌ Avoid - Missing cleanup
434
- useEffect(() => {
435
- setTimeout(() => {
436
- // do something
437
- }, 1000);
438
- }, []);
439
- ```
440
-
441
- ### Performance
442
-
443
- ```tsx
444
- // ✅ Good - Memoized expensive operations
445
- const expensiveValue = useMemo(() => {
446
- return computeExpensiveValue(data);
447
- }, [data]);
448
-
449
- // ❌ Avoid - Recomputing on every render
450
- const expensiveValue = computeExpensiveValue(data);
451
- ```
33
+ ## Available exports
452
34
 
453
- ## Contributing
35
+ - `useDebouncedValue` — debounce a changing value.
36
+ - `useLocalStorage` — state persisted to `localStorage`.
37
+ - `useMediaQuery` — reactively match a media query.
38
+ - `useClickOutside` — run a callback on clicks outside a ref.
39
+ - `useIsMobile` — boolean for a mobile-width viewport.
40
+ - `useFormField` — access form-field context (with `FormFieldContext`,
41
+ `FormItemContext`, and the `FormFieldContextValue` / `FormItemContextValue`
42
+ types).
43
+ - `useAdvancedSearch` — search state and behaviour (with `SearchContext` and the
44
+ `EmptyStateBehavior` / `EmptyStateBehaviour` types).
45
+ - Re-exported types: `SearchResult`, `SearchSection` (from
46
+ `@foundrykit/types`).
47
+ - `noop` — a no-operation utility function.
454
48
 
455
- When adding new hooks:
49
+ ## Documentation
456
50
 
457
- 1. Follow React hooks best practices
458
- 2. Include comprehensive TypeScript definitions
459
- 3. Add JSDoc documentation
460
- 4. Write unit tests
461
- 5. Include usage examples
462
- 6. Update this README
51
+ Each hook is documented with JSDoc at its point of export; hover in your editor
52
+ for signatures and usage notes. See `src/index.ts` for the full export surface.
463
53
 
464
54
  ## License
465
55