Skip to content
Merged
Show file tree
Hide file tree
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
41 changes: 41 additions & 0 deletions src/react-native/focus-effect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { useEffect } from "react";

const getDefaultFocusEffectFactory = (): ((cb: () => void) => void) => {
try {
return require("expo-router").useFocusEffect;
} catch {
// Nothing we can do about it, it's not installed in the project.
}

try {
return require("@react-navigation/native").useFocusEffect;
} catch {
// Nothing we can do about it, it's not installed in the project.
}

console.warn(
"[react-native-grab] No supported router found — falling back to useEffect. This may cause issues. Provide a custom focus effect using the setFocusEffect function.",
);

const useFallbackFocusEffect = (cb: () => void) => {
useEffect(() => {
return cb();
}, [cb]);
};

return useFallbackFocusEffect;
};

let cachedFocusEffect: ((cb: () => void) => void) | null = null;

export const getFocusEffect = (): ((cb: () => void) => void) => {
if (!cachedFocusEffect) {
cachedFocusEffect = getDefaultFocusEffectFactory();
}

return cachedFocusEffect;
};

export const setFocusEffect = (impl: (cb: () => void) => void) => {
cachedFocusEffect = impl;
};
19 changes: 2 additions & 17 deletions src/react-native/grab-screen.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,9 @@
import { useCallback, useRef } from "react";
import { View, type ViewProps } from "react-native";
import { setFocusedScreenRef } from "./containers";
import { getFocusEffect } from "./focus-effect";

const getFocusEffectImpl = (): ((cb: () => void) => void) => {
try {
return require("expo-router").useFocusEffect;
} catch {
// Nothing we can do about it, it's not installed in the project.
}

try {
return require("@react-navigation/native").useFocusEffect;
} catch {
// Nothing we can do about it, it's not installed in the project.
}

throw new Error("No useFocusEffect implementation found");
};

const useFocusEffect = getFocusEffectImpl();
const useFocusEffect = getFocusEffect();

export type ReactNativeGrabScreenProps = ViewProps;

Expand Down
4 changes: 4 additions & 0 deletions src/react-native/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,7 @@ export const ReactNativeGrabContextProvider: React.ComponentType<ReactNativeGrab
export const enableGrabbing: () => void = __DEV__
? require("./grab-controller").enableGrabbing
: noop;

export const setFocusEffect: (impl: (cb: () => void) => void) => void = __DEV__
? require("./focus-effect").setFocusEffect
: noop;
Loading