1
1
// Imports
2
- import React , { useState , useRef , createRef , useEffect } from 'react' ;
2
+ import React , { useState , useRef , createRef , useEffect , useMemo } from 'react' ;
3
3
4
4
// Create interface for button properties
5
5
interface ButtonProps
@@ -32,12 +32,10 @@ export default function useDropdownMenu(itemCount: number): DropdownMenuResponse
32
32
33
33
// Create refs
34
34
const buttonRef = useRef < HTMLButtonElement > ( null ) ;
35
- const itemRefs = useRef < React . RefObject < HTMLAnchorElement > [ ] > ( [ ] ) ;
36
-
37
- // Initialize refs and update them when the item count changes
38
- useEffect ( ( ) => {
39
- itemRefs . current = Array . from ( { length : itemCount } , ( ) => createRef < HTMLAnchorElement > ( ) ) ;
40
- } , [ itemCount ] ) ;
35
+ const itemRefs = useMemo < React . RefObject < HTMLAnchorElement > [ ] > (
36
+ ( ) => Array . from ( { length : itemCount } , ( ) => createRef < HTMLAnchorElement > ( ) ) ,
37
+ [ itemCount ]
38
+ ) ;
41
39
42
40
// Create type guard
43
41
const isKeyboardEvent = ( e : React . KeyboardEvent | React . MouseEvent ) : e is React . KeyboardEvent =>
@@ -46,7 +44,7 @@ export default function useDropdownMenu(itemCount: number): DropdownMenuResponse
46
44
// Handles moving the focus between menu items
47
45
const moveFocus = ( itemIndex : number ) : void => {
48
46
currentFocusIndex . current = itemIndex ;
49
- itemRefs . current [ itemIndex ] . current ?. focus ( ) ;
47
+ itemRefs [ itemIndex ] . current ?. focus ( ) ;
50
48
} ;
51
49
52
50
// Focus the first item when the menu opens
@@ -175,10 +173,10 @@ export default function useDropdownMenu(itemCount: number): DropdownMenuResponse
175
173
newFocusIndex += 1 ;
176
174
}
177
175
178
- if ( newFocusIndex > itemRefs . current . length - 1 ) {
176
+ if ( newFocusIndex > itemRefs . length - 1 ) {
179
177
newFocusIndex = 0 ;
180
178
} else if ( newFocusIndex < 0 ) {
181
- newFocusIndex = itemRefs . current . length - 1 ;
179
+ newFocusIndex = itemRefs . length - 1 ;
182
180
}
183
181
}
184
182
@@ -203,7 +201,7 @@ export default function useDropdownMenu(itemCount: number): DropdownMenuResponse
203
201
onKeyDown : itemListener ,
204
202
tabIndex : - 1 ,
205
203
role : 'menuitem' ,
206
- ref : itemRefs . current [ index ] ,
204
+ ref : itemRefs [ index ] ,
207
205
} ) ) ;
208
206
209
207
// Return a listener for the button, individual list items, and the state of the menu
0 commit comments