11// Imports
2- import React , { useState , useRef , createRef , useEffect } from 'react' ;
2+ import React , { useState , useRef , createRef , useEffect , useMemo } from 'react' ;
33
44// Create interface for button properties
55interface ButtonProps
@@ -32,12 +32,10 @@ export default function useDropdownMenu(itemCount: number): DropdownMenuResponse
3232
3333 // Create refs
3434 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+ ) ;
4139
4240 // Create type guard
4341 const isKeyboardEvent = ( e : React . KeyboardEvent | React . MouseEvent ) : e is React . KeyboardEvent =>
@@ -46,7 +44,7 @@ export default function useDropdownMenu(itemCount: number): DropdownMenuResponse
4644 // Handles moving the focus between menu items
4745 const moveFocus = ( itemIndex : number ) : void => {
4846 currentFocusIndex . current = itemIndex ;
49- itemRefs . current [ itemIndex ] . current ?. focus ( ) ;
47+ itemRefs [ itemIndex ] . current ?. focus ( ) ;
5048 } ;
5149
5250 // Focus the first item when the menu opens
@@ -175,10 +173,10 @@ export default function useDropdownMenu(itemCount: number): DropdownMenuResponse
175173 newFocusIndex += 1 ;
176174 }
177175
178- if ( newFocusIndex > itemRefs . current . length - 1 ) {
176+ if ( newFocusIndex > itemRefs . length - 1 ) {
179177 newFocusIndex = 0 ;
180178 } else if ( newFocusIndex < 0 ) {
181- newFocusIndex = itemRefs . current . length - 1 ;
179+ newFocusIndex = itemRefs . length - 1 ;
182180 }
183181 }
184182
@@ -203,7 +201,7 @@ export default function useDropdownMenu(itemCount: number): DropdownMenuResponse
203201 onKeyDown : itemListener ,
204202 tabIndex : - 1 ,
205203 role : 'menuitem' ,
206- ref : itemRefs . current [ index ] ,
204+ ref : itemRefs [ index ] ,
207205 } ) ) ;
208206
209207 // Return a listener for the button, individual list items, and the state of the menu
0 commit comments