@@ -52,34 +52,44 @@ export const useList = (query?: firebase.database.Query | null): ListHook => {
5252 } ;
5353
5454 let childAddedHandler : ReturnType < typeof ref . on > | undefined ;
55- const children : firebase . database . DataSnapshot [ ] = [ ] ;
5655 const onInitialLoad = ( snapshot : firebase . database . DataSnapshot ) => {
57- let childrenToProcess = Object . keys ( snapshot . val ( ) ) . length ;
58-
59- const onChildAddedWithoutInitialLoad = (
60- addedChild : firebase . database . DataSnapshot ,
61- previousKey ?: string | null
62- ) => {
63- // process the first batch of children all at once
64- if ( childrenToProcess > 0 ) {
65- childrenToProcess -- ;
66- children . push ( addedChild ) ;
67-
68- if ( childrenToProcess === 0 ) {
69- onValue ( children ) ;
56+ const snapshotVal = snapshot . val ( ) ;
57+ let childrenToProcess = snapshotVal
58+ ? Object . keys ( snapshot . val ( ) ) . length
59+ : 0 ;
60+
61+ // If the list is empty then initialise the hook and use the default `onChildAdded` behaviour
62+ if ( childrenToProcess === 0 ) {
63+ childAddedHandler = ref . on ( 'child_added' , onChildAdded , onError ) ;
64+ onValue ( [ ] ) ;
65+ } else {
66+ // Otherwise, we load the first batch of children all to reduce re-renders
67+ const children : firebase . database . DataSnapshot [ ] = [ ] ;
68+
69+ const onChildAddedWithoutInitialLoad = (
70+ addedChild : firebase . database . DataSnapshot ,
71+ previousKey ?: string | null
72+ ) => {
73+ if ( childrenToProcess > 0 ) {
74+ childrenToProcess -- ;
75+ children . push ( addedChild ) ;
76+
77+ if ( childrenToProcess === 0 ) {
78+ onValue ( children ) ;
79+ }
80+
81+ return ;
7082 }
7183
72- return ;
73- }
84+ onChildAdded ( snapshot , previousKey ) ;
85+ } ;
7486
75- onChildAdded ( snapshot , previousKey ) ;
76- } ;
77-
78- childAddedHandler = ref . on (
79- 'child_added' ,
80- onChildAddedWithoutInitialLoad ,
81- onError
82- ) ;
87+ childAddedHandler = ref . on (
88+ 'child_added' ,
89+ onChildAddedWithoutInitialLoad ,
90+ onError
91+ ) ;
92+ }
8393 } ;
8494
8595 ref . once ( 'value' , onInitialLoad , onError ) ;
0 commit comments