1
- import React from 'react'
1
+ import React , { useMemo } from 'react'
2
2
import createPersistedState from 'use-persisted-state' ;
3
3
import dayjs from 'dayjs'
4
4
@@ -9,6 +9,9 @@ import {UserStateActions, UserStateActionsContextProvider} from './user-state-ac
9
9
const useBirthDateState = createPersistedState ( 'BirthDate' , global . sessionStorage ) ;
10
10
const useRetireDateState = createPersistedState ( 'RetireDate' , global . sessionStorage ) ;
11
11
12
+ /**
13
+ * Helper function to get a Date object equivalent to the start of the date given
14
+ */
12
15
function startOfDay ( date : Date ) : Date {
13
16
return dayjs ( date ) . startOf ( 'day' ) . toDate ( )
14
17
}
@@ -17,17 +20,21 @@ interface UserStateManagerProps {
17
20
children : React . ReactNode
18
21
}
19
22
23
+ /**
24
+ * Serve as a multi-context provider for descendent components, providing them with access to
25
+ * the user state and a set of actions to mutate that state, while persisting it to session storage.
26
+ */
20
27
export default function UserStateManager ( props : UserStateManagerProps ) : JSX . Element {
21
28
const { children} = props
22
29
const [ birthDate , setBirthDate ] = useBirthDateState < Date | null > ( null )
23
30
const [ retireDate , setRetireDate ] = useRetireDateState < Date | null > ( null )
24
31
25
- const actions : UserStateActions = {
32
+ const actions : UserStateActions = useMemo ( ( ) => ( {
26
33
setBirthDate : date => setBirthDate ( startOfDay ( date ) ) ,
27
34
setRetireDate : date => setRetireDate ( startOfDay ( date ) ) ,
28
- }
35
+ } ) , [ setBirthDate , setRetireDate ] )
29
36
30
- const userState : UserState = React . useMemo ( ( ) => ( {
37
+ const userState : UserState = useMemo ( ( ) => ( {
31
38
birthDate : birthDate ? new Date ( birthDate ) : null ,
32
39
retireDate : retireDate ? new Date ( retireDate ) : null ,
33
40
} ) , [ birthDate , retireDate ] )
0 commit comments