From b35570c4944663d7a76e429098aa7827bb95db7b Mon Sep 17 00:00:00 2001 From: Mir Sahib Date: Thu, 10 Jul 2025 18:42:11 +0600 Subject: [PATCH] :bug: Fix Re-initialize camera on focus & resolve CameraView children issue Re-initializes CameraView on screen focus using useFocusEffect and wraps CameraView with controls in a fragment to address children limitation. --- with-camera/App.tsx | 106 ++++++++++++++++++++++++++------------------ 1 file changed, 63 insertions(+), 43 deletions(-) diff --git a/with-camera/App.tsx b/with-camera/App.tsx index 8d96d57a..c62fdb7f 100644 --- a/with-camera/App.tsx +++ b/with-camera/App.tsx @@ -4,9 +4,10 @@ import { CameraView, useCameraPermissions, } from "expo-camera"; -import { useRef, useState } from "react"; +import { useRef, useState,useCallback } from "react"; import { Button, Pressable, StyleSheet, Text, View } from "react-native"; import { Image } from "expo-image"; +import { useFocusEffect } from "expo-router"; import AntDesign from "@expo/vector-icons/AntDesign"; import Feather from "@expo/vector-icons/Feather"; import FontAwesome6 from "@expo/vector-icons/FontAwesome6"; @@ -18,6 +19,14 @@ export default function App() { const [mode, setMode] = useState("picture"); const [facing, setFacing] = useState("back"); const [recording, setRecording] = useState(false); + const [cameraKey, setCameraKey] = useState(0); + //Used to force CameraView re-mount on screen focus change + useFocusEffect( + useCallback(() => { + // Regenerate key when screen is focused + setCameraKey((prev) => prev + 1); + }, []) + ); if (!permission) { return null; @@ -73,48 +82,59 @@ export default function App() { const renderCamera = () => { return ( - - - - {mode === "picture" ? ( - - ) : ( - - )} - - - {({ pressed }) => ( - - - - )} - - - - - - + <> + + + + {mode === "picture" ? ( + + ) : ( + + )} + + + {({ pressed }) => ( + + + + )} + + + + + + ); };