Skip to content

Instantly share code, notes, and snippets.

@btoo
Last active June 12, 2024 04:43
Show Gist options
  • Save btoo/7f713027e8bcf8f4b3c94b5ce51d3917 to your computer and use it in GitHub Desktop.
Save btoo/7f713027e8bcf8f4b3c94b5ce51d3917 to your computer and use it in GitHub Desktop.
react native keyboard height hook
import { useEffect } from "react";
import { Keyboard } from "react-native";
import { useState } from "./mounted";
export function useKeyboardHeight() {
const [keyboardHeight, setKeyboardHeight] = useState(0);
useEffect(() => {
const showSubscription = Keyboard.addListener('keyboardDidShow', e => setKeyboardHeight(e.endCoordinates.height));
const hideSubscription = Keyboard.addListener('keyboardWillHide', () => setKeyboardHeight(0));
return () => {
showSubscription.remove();
hideSubscription.remove();
}
}, [setKeyboardHeight]);
return keyboardHeight;
}
@artfxx
Copy link

artfxx commented Sep 11, 2022

keyboardDidHide instead of keyboardWillHide
dependency [setKeyboardHeight] in useEffect is not needed [ ]

@Irfanwani
Copy link

keyboardDidHide instead of keyboardWillHide dependency [setKeyboardHeight] in useEffect is not needed [ ]

I think it is better to use KeyboardWillHide and KeyboardWillShow as this is going to remove the delay in styles, if applying, based on the keyboard height.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment