Skip to content

Instantly share code, notes, and snippets.

@harrisrobin
Last active August 9, 2023 14:19
Show Gist options
  • Save harrisrobin/3c3b1c004f74416629d6d18f85ec382d to your computer and use it in GitHub Desktop.
Save harrisrobin/3c3b1c004f74416629d6d18f85ec382d to your computer and use it in GitHub Desktop.
React-Navigation screen cache component (wrap every screen with this to avoid re-creating new screens when react-navigation re-renders).
import React from "react"
import { SafeAreaProvider } from "react-native-safe-area-context"
// Cache the wrapper component to avoid creating a new one every time a screen
// is created.
const componentsCache = new WeakMap<
React.ComponentType<any>,
React.ComponentType<any>
>()
export function getScreenComponent(
getComponent: () => React.ComponentType<any>,
): () => React.ComponentType<any> {
return () => {
const Component = getComponent()
const CachedComponent = componentsCache.get(Component)
if (CachedComponent != null) {
return CachedComponent
}
function ScreenComponent(props: any) {
return (
<SafeAreaProvider>
<Component {...props} />
</SafeAreaProvider>
)
}
componentsCache.set(Component, ScreenComponent)
return ScreenComponent
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment