Created
February 27, 2025 07:55
-
-
Save Wurushu/465442f34453b8dbd9d3d3be0b344950 to your computer and use it in GitHub Desktop.
React component prevent re-render with useRef, useCallback, useMemo trick.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useCallback, useRef, useMemo } from "react"; | |
import { View } from "react-native"; | |
import { Appbar } from "react-native-paper"; | |
import { Stack, useNavigation } from "expo-router"; | |
export default function App(): React.JSX.Element { | |
const navigation = useNavigation(); | |
const [stage, setStage] = React.useState(0); | |
const stageRef = useRef(stage); | |
useEffect(() => { | |
stageRef.current = stage; | |
}, [stage]); | |
const handlePress = useCallback(() => { | |
if (stageRef.current === 0) { | |
navigation.goBack(); | |
} else { | |
setStage(0); | |
} | |
}, [navigation]); | |
const headerLeft = useMemo(() => { | |
return () => <Appbar.BackAction onPress={handlePress} />; | |
}, [handlePress]); | |
return ( | |
<View> | |
<Stack.Screen | |
options={{ | |
headerLeft, | |
}} | |
/> | |
{/* Content */} | |
</View> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment