react-native-keyevent
react-native-keyevent copied to clipboard
Registering multiple listeners at once (for example in different screens)
I have a custom hook useKeyEventListener that looks more of less like this:
const useKeyEventListener = () => {
useEffect(() => {
KeyEvent.onKeyDownListener(() => { /* do stuff */ })
return () => {
KeyEvent.removeKeyDownListener()
}
}, [])
}
I've noticed that when I mount this hook in multiple screens, the listener stops working in all screens after it's been removed in one screen.
For example:
- call useKeyEventListener hook in HomeScreen
- nav to DetailScreen, call useKeyEventListener hook
- close DetailScreen, the cleanup phase of useKeyEventListener removes the listener
- back in the HomeScreen useKeyEventListener does not work anymore also the hook is still called
So I'm guessing the native code in this library only allows to have one single listener. As soon as it is removed, it stops firing and needs to be explicitly "re-added" to start again.
So my questions are:
- Is it possible to have multiple listeners registered at once, and if so how can they be identified so that
KeyEvent.removeKeyDownListenerremoves a particular listener? - If the library doesn't support registering multiple listeners at once, what strategies would you recommend to achieve that anyways? (Maybe having a global React Context
KeyEventListenerContextthat tracks which screen is focused and sends key events to that screen, not to others)