Skip to content

Instantly share code, notes, and snippets.

@Wurushu
Created February 27, 2025 07:55
Show Gist options
  • Save Wurushu/465442f34453b8dbd9d3d3be0b344950 to your computer and use it in GitHub Desktop.
Save Wurushu/465442f34453b8dbd9d3d3be0b344950 to your computer and use it in GitHub Desktop.
React component prevent re-render with useRef, useCallback, useMemo trick.
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