Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 71 ยท Native Features

Camera, Location and Sensors

Use the camera, GPS, image picker and motion sensors in React Native with Expo, and handle every permission state: undetermined, granted, denied and blocked.

A phone is far more than a screen. It has a camera, a GPS receiver, an accelerometer, a gyroscope and a compass, and your app can use all of them. This is where React Native starts to feel different from the web: each of these features sits behind a native module that you reach from JavaScript, and almost all of them need the user's explicit permission first.

In this lesson you meet the Expo libraries for the camera (expo-camera), position (expo-location), picking photos (expo-image-picker) and motion (expo-sensors). The part that matters most, and the part beginners skip, is the permission flow: what to do when the answer is not yet known, yes, no, or "no, and never ask again".

Read-only and stand-in. Camera, GPS and sensors need real hardware, so the real library code is shown in plain code blocks. The TryIts run small stand-ins in your browser: a permission state machine and a stream of fake accelerometer samples. They show the logic around the hardware, not the hardware itself.

The permission model

Every protected feature follows the same three steps on iOS and Android:

  1. Declare the feature in your app config. iOS needs a human-readable reason (a usage description string); Android needs an entry in the manifest. With Expo, config plugins write these for you (see Native Modules, Expo Modules and Config Plugins).
  2. Ask at the moment the feature is needed, not on first launch. A user who just tapped "Scan code" understands why you want the camera.
  3. Handle every answer. The status is one of three values:
Status Meaning
undetermined The user has never been asked.
granted The user said yes.
denied The user said no.

Alongside the status, Expo libraries return a boolean canAskAgain. When it is false, the system will not show the dialog again, and the only way forward is to send the user to the Settings app with Linking.openSettings() (see Platform APIs).

The two systems differ in a useful way. iOS asks once: a denial is final until the user changes it in Settings. Android lets you ask a second time after the first denial, and then the user can tick "don't ask again", or the system stops asking after repeated denials.

Every permission, three steps

Declare Usage text on iOS, manifest entry on Android.
Ask When the feature is first needed.
Handle Granted, denied, or blocked.

Never assume "granted". Design the denied screen first.

1 / 2

The camera

expo-camera exports a CameraView component and a hook that manages the permission.

TSX
import { CameraView, useCameraPermissions } from 'expo-camera';
import { useRef, useState } from 'react';
import { Button, Image, Linking, Text, View } from 'react-native';

export default function Scanner() {
  const [permission, requestPermission] = useCameraPermissions();
  const cameraRef = useRef<CameraView>(null);
  const [photoUri, setPhotoUri] = useState<string | null>(null);

  if (!permission) {
    return <View />; // still reading the saved status
  }

  if (!permission.granted) {
    return (
      <View>
        <Text>We use the camera to scan receipts.</Text>
        {permission.canAskAgain ? (
          <Button title="Allow camera" onPress={requestPermission} />
        ) : (
          <Button title="Open Settings" onPress={() => Linking.openSettings()} />
        )}
      </View>
    );
  }

  async function takePhoto() {
    const photo = await cameraRef.current?.takePictureAsync();
    if (photo) setPhotoUri(photo.uri);
  }

  return (
    <View style={{ flex: 1 }}>
      <CameraView ref={cameraRef} style={{ flex: 1 }} facing="back" />
      <Button title="Take photo" onPress={takePhoto} />
      {photoUri && <Image source={{ uri: photoUri }} style={{ height: 120 }} />}
    </View>
  );
}

Notice the three early returns. permission is null while the saved status loads, granted is false until the user agrees, and canAskAgain decides whether the button asks or opens Settings. The camera itself only mounts after all of that. The takePictureAsync call resolves to an object whose uri points at a file in the app's cache.

The config plugin supplies the iOS usage text and the Android permission:

JSON
{
  "expo": {
    "plugins": [
      ["expo-camera", { "cameraPermission": "Allow $(PRODUCT_NAME) to scan receipts." }]
    ]
  }
}

A camera does not work in an iOS simulator because it has no camera. Test on a real phone, or on an Android emulator that offers a virtual camera.

Picking photos

Many apps do not need a live camera, only a picture. expo-image-picker opens the system's own photo picker, which is faster to build and friendlier to privacy.

TSX
import * as ImagePicker from 'expo-image-picker';

async function pickAvatar() {
  const result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: ['images'],
    allowsEditing: true,
    aspect: [1, 1],
    quality: 0.8,
  });

  if (result.canceled) return null; // the user backed out
  return result.assets[0].uri;
}

Always check canceled first: backing out of the picker is a normal outcome, not an error. On current iOS and Android versions the library picker is a system component that grants access to only the photos the user chooses, so it does not need a permission prompt. Taking a new photo with launchCameraAsync, however, uses the camera and does need permission, which you request with ImagePicker.requestCameraPermissionsAsync().

Prefer a modest quality (below 1) and sensible limits. A full-resolution photo can be several megabytes, and you will pay for that in uploads.

Location

expo-location gives you the position, and it separates foreground access (while the app is on screen) from background access (while it is not).

TSX
import * as Location from 'expo-location';

async function getCoordinates() {
  const { status } = await Location.requestForegroundPermissionsAsync();
  if (status !== 'granted') {
    throw new Error('Location permission was not granted');
  }

  const position = await Location.getCurrentPositionAsync({
    accuracy: Location.Accuracy.Balanced,
  });
  return position.coords; // { latitude, longitude, accuracy, ... }
}

For continuous updates, watchPositionAsync returns a subscription that you must remove, exactly like the listeners in Platform APIs:

TSX
useEffect(() => {
  let subscription: Location.LocationSubscription | undefined;

  (async () => {
    subscription = await Location.watchPositionAsync(
      { accuracy: Location.Accuracy.High, distanceInterval: 20 },
      (position) => setCoords(position.coords),
    );
  })();

  return () => subscription?.remove();
}, []);

Think about accuracy as a budget. High accuracy keeps the GPS chip on and drains the battery, while a lower level uses Wi-Fi and cell towers and is usually enough for "stores near you". distanceInterval (in meters) stops callbacks until the user has actually moved.

Background location is a much bigger step. It needs a separate request (requestBackgroundPermissionsAsync), extra declarations, a registered background task, and a justification during store review. Ask for it only when the product truly needs it, such as a run tracker.

Motion sensors

expo-sensors exposes the accelerometer, gyroscope, magnetometer, barometer and pedometer through one pattern: set an update interval, add a listener, and remove it later.

TSX
import { Accelerometer } from 'expo-sensors';
import { useEffect, useState } from 'react';

export function useTilt() {
  const [reading, setReading] = useState({ x: 0, y: 0, z: 0 });

  useEffect(() => {
    Accelerometer.setUpdateInterval(100); // milliseconds between samples
    const subscription = Accelerometer.addListener(setReading);
    return () => subscription.remove();
  }, []);

  return reading;
}

The accelerometer reports acceleration in units of g (one g is Earth's gravity). A phone lying face up reads close to { x: 0, y: 0, z: -1 } or +1, depending on the platform's sign convention, because gravity always pulls on it. A shake shows up as a sudden jump in the magnitude, the square root of xยฒ + yยฒ + zยฒ. Sensors keep the hardware awake, so use the slowest update interval that still feels responsive, and always unsubscribe when the screen goes away.

Stand-in: a permission state machine

The code below is not the real library. It models the two platform behaviors described earlier: iOS asks once, Android may ask again before it blocks. A PermissionGate then decides what to render for each state, which is the logic you would put in the component above.

Permission states on iOS and Android

The first Android scenario is the interesting one: the user denied once, allowed on the retry, and the app works. On iOS the same "deny, then allow" sequence ends with a blocked state, because the system never showed the second dialog. That is why a pre-permission screen, a short explanation shown before the system dialog, is worth building on iOS: you only get one chance.

Stand-in: a stream of accelerometer samples

Real sensors push samples to a listener. The stand-in below does the same with a fixed list, then applies the shake test from the previous section. Because the data is fixed, the output is the same every run.

Detecting a shake from accelerometer samples

The resting samples sit near 1 g, and only the violent ones cross the threshold. In a real app you would also debounce: ignore further shakes for half a second so one gesture triggers one action.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A user denied the camera permission and permission.canAskAgain is false. What should your screen offer?

    The system will not show the dialog again, so the only way to change the answer is through Settings, reached with Linking.openSettings().
  2. 2. When is the best moment to ask for camera access?

    Asking in context lets the user understand the reason, and users grant permission far more often than not.
  3. 3. Why must you call subscription.remove() for watchPositionAsync or an Accelerometer listener?

    Subscriptions keep the sensor or GPS active and keep calling your callback. Removing them in the effect cleanup stops both the battery drain and the stale updates.
  4. 4. What does result.canceled mean after launchImageLibraryAsync?

    Backing out is a normal outcome, so check canceled before reading result.assets.

Summary

  • Device features live in native modules reached through Expo libraries: expo-camera, expo-location, expo-image-picker and expo-sensors.
  • Permissions follow declare, ask in context, handle every answer. The statuses are undetermined, granted and denied, plus canAskAgain.
  • iOS asks once; Android may ask again before it blocks. When canAskAgain is false, send users to Settings.
  • The system photo picker needs no permission; taking a new photo does.
  • Choose location accuracy and sensor intervals deliberately, and remove every subscription on cleanup.
  • Simulators lack a camera and real sensors, so test hardware features on a device.

Next, learn how an app reaches the user when it is closed in Push Notifications.