Skip to content

Commit c89b238

Browse files
committed
chore: [useKeyboard] Reduce re-renders amount
1 parent 61b6ef5 commit c89b238

File tree

1 file changed

+29
-25
lines changed

1 file changed

+29
-25
lines changed

src/useKeyboard.ts

Lines changed: 29 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,52 @@
11
import {useEffect, useState} from 'react'
22
import {Keyboard, KeyboardEventListener, KeyboardMetrics} from 'react-native'
33

4-
const emptyCoordinates = Object.freeze({
4+
const emptyCoordinates: KeyboardMetrics = Object.freeze({
55
screenX: 0,
66
screenY: 0,
77
width: 0,
88
height: 0,
99
})
1010
const initialValue = {
11-
start: emptyCoordinates,
11+
start: emptyCoordinates as KeyboardMetrics | undefined,
1212
end: emptyCoordinates,
1313
}
14+
const defaultState = {
15+
keyboardShown: false,
16+
coordinates: initialValue,
17+
keyboardHeight: 0,
18+
}
1419

1520
export function useKeyboard() {
16-
const [shown, setShown] = useState(false)
17-
const [coordinates, setCoordinates] = useState<{
18-
start: undefined | KeyboardMetrics
19-
end: KeyboardMetrics
20-
}>(initialValue)
21-
const [keyboardHeight, setKeyboardHeight] = useState<number>(0)
21+
const [state, setState] = useState(defaultState)
2222

2323
const handleKeyboardWillShow: KeyboardEventListener = (e) => {
24-
setCoordinates({start: e.startCoordinates, end: e.endCoordinates})
24+
setState((prevState) => ({
25+
...prevState,
26+
coordinates: {start: e.startCoordinates, end: e.endCoordinates},
27+
}))
2528
}
2629
const handleKeyboardDidShow: KeyboardEventListener = (e) => {
27-
setShown(true)
28-
setCoordinates({start: e.startCoordinates, end: e.endCoordinates})
29-
setKeyboardHeight(e.endCoordinates.height)
30+
setState(() => ({
31+
keyboardShown: true,
32+
coordinates: {start: e.startCoordinates, end: e.endCoordinates},
33+
keyboardHeight: e.endCoordinates.height,
34+
}))
3035
}
3136
const handleKeyboardWillHide: KeyboardEventListener = (e) => {
32-
setCoordinates({start: e.startCoordinates, end: e.endCoordinates})
37+
setState((prevState) => ({
38+
...prevState,
39+
coordinates: {start: e.startCoordinates, end: e.endCoordinates},
40+
}))
3341
}
3442
const handleKeyboardDidHide: KeyboardEventListener = (e) => {
35-
setShown(false)
36-
if (e) {
37-
setCoordinates({start: e.startCoordinates, end: e.endCoordinates})
38-
} else {
39-
setCoordinates(initialValue)
40-
setKeyboardHeight(0)
41-
}
43+
setState((prevState) => ({
44+
keyboardShown: false,
45+
coordinates: e
46+
? {start: e.startCoordinates, end: e.endCoordinates}
47+
: initialValue,
48+
keyboardHeight: e ? prevState.keyboardHeight : 0,
49+
}))
4250
}
4351

4452
useEffect(() => {
@@ -54,9 +62,5 @@ export function useKeyboard() {
5462
}
5563
}, [])
5664

57-
return {
58-
keyboardShown: shown,
59-
coordinates,
60-
keyboardHeight,
61-
}
65+
return state
6266
}

0 commit comments

Comments
 (0)