Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: set shared values in layout effects #838

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 21 additions & 14 deletions src/components/KeyboardAvoidingView/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState } from "react";
import { useLayoutEffect } from "react";
import { Platform } from "react-native";
import { useSharedValue } from "react-native-reanimated";

Expand All @@ -10,22 +10,28 @@ const OS = Platform.OS;
export const useKeyboardAnimation = () => {
const { reanimated } = useKeyboardContext();

// calculate it only once on mount, to avoid `SharedValue` reads during a render
const [initialHeight] = useState(() => -reanimated.height.value);
const [initialProgress] = useState(() => reanimated.progress.value);
const heightWhenOpened = useSharedValue(0);
const height = useSharedValue(0);
const progress = useSharedValue(0);
const isClosed = useSharedValue(true);

const heightWhenOpened = useSharedValue(initialHeight);
const height = useSharedValue(initialHeight);
const progress = useSharedValue(initialProgress);
const isClosed = useSharedValue(initialProgress === 0);
useLayoutEffect(() => {
const initialHeight = -reanimated.height.value;
const initialProgress = reanimated.progress.value;

// eslint-disable-next-line react-compiler/react-compiler
heightWhenOpened.value = initialHeight;
height.value = initialHeight;
progress.value = initialProgress;
isClosed.value = initialProgress === 0;
}, []);

useKeyboardHandler(
{
onStart: (e) => {
"worklet";

if (e.height > 0) {
// eslint-disable-next-line react-compiler/react-compiler
isClosed.value = false;
heightWhenOpened.value = e.height;
}
Expand Down Expand Up @@ -59,19 +65,20 @@ export const useKeyboardAnimation = () => {
export const useTranslateAnimation = () => {
const { reanimated } = useKeyboardContext();

// calculate it only once on mount, to avoid `SharedValue` reads during a render
const [initialProgress] = useState(() => reanimated.progress.value);

const padding = useSharedValue(initialProgress);
const padding = useSharedValue(0);
const translate = useSharedValue(0);

useLayoutEffect(() => {
// eslint-disable-next-line react-compiler/react-compiler
padding.value = reanimated.progress.value;
}, []);

useKeyboardHandler(
{
onStart: (e) => {
"worklet";

if (e.height === 0) {
// eslint-disable-next-line react-compiler/react-compiler
padding.value = 0;
}
if (OS === "ios") {
Expand Down