Guides
Plan-enterprise-icon
Expo Application Services
API Reference

LightSensor

LightSensor from expo-sensors provides access to the device's light sensor to respond to illuminance changes.

Platform Compatibility

Android DeviceAndroid EmulatoriOS DeviceiOS SimulatorWeb
Status-success-iconStatus-success-iconStatus-failed-iconStatus-failed-iconStatus-failed-icon

Installation

Terminal
→ npx expo install expo-sensors

If you're installing this in a bare React Native app, you should also follow these additional installation instructions.

Usage

Basic Light Sensor usage
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, TouchableOpacity, View, Platform } from 'react-native';
import { LightSensor } from 'expo-sensors';

export default function App() {
  const [{ illuminance }, setData] = useState({ illuminance: 0 });

  useEffect(() => {
    _toggle();

    return () => {
      _unsubscribe();
    };
  }, []);

  const _toggle = () => {
    if (this._subscription) {
      _unsubscribe();
    } else {
      _subscribe();
    }
  };

  const _subscribe = () => {
    this._subscription = LightSensor.addListener(setData);
  };

  const _unsubscribe = () => {
    this._subscription && this._subscription.remove();
    this._subscription = null;
  };

  return (
    <View style={styles.sensor}>
      <Text>Light Sensor:</Text>
      <Text>
        Illuminance: {Platform.OS === 'android' ? `${illuminance} lx` : `Only available on Android`}
      </Text>
      <View style={styles.buttonContainer}>
        <TouchableOpacity onPress={_toggle} style={styles.button}>
          <Text>Toggle</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}

%%placeholder-start%%const styles = StyleSheet.create({ ... }); %%placeholder-end%%const styles = StyleSheet.create({
  buttonContainer: {
    flexDirection: 'row',
    alignItems: 'stretch',
    marginTop: 15,
  },
  button: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#eee',
    padding: 10,
  },
  sensor: {
    marginTop: 45,
    paddingHorizontal: 10,
  },
});

API

import { LightSensor } from 'expo-sensors';

Classes

LightSensor

Type: Class extends DeviceSensor<LightSensorMeasurement>

Only for:
Android-iconAndroid

LightSensor Methods

addListener(listener)

NameTypeDescription
listenerListener<LightSensorMeasurement>

A callback that is invoked when a LightSensor update is available. When invoked, the listener is provided a single argument that is the illuminance value.

Subscribe for updates to the light sensor.

  • Undo-iconSubscription

A subscription that you can call remove() on when you would like to unsubscribe the listener.

getListenerCount()

Returns the registered listeners count.

  • Undo-iconnumber

getPermissionsAsync()

Checks user's permissions for accessing sensor.

hasListeners()

Returns boolean which signifies if sensor has any listeners registered.

  • Undo-iconboolean

isAvailableAsync()

Info-icon
You should always check the sensor availability before attempting to use it.

Returns whether the light sensor is available and enabled on the device. Requires at least Android 2.3 (API Level 9).

A promise that resolves to a boolean denoting the availability of the light sensor.

removeAllListeners()

Removes all registered listeners.

  • Undo-iconvoid

removeSubscription(subscription)

NameTypeDescription
subscriptionSubscription

A subscription to remove.

Removes the given subscription.

  • Undo-iconvoid

requestPermissionsAsync()

Asks the user to grant permissions for accessing sensor.

setUpdateInterval(intervalMs)

NameTypeDescription
intervalMsnumber

Desired interval in milliseconds between sensor updates.

Info-icon

Starting from Android 12 (API level 31), the system has a 200ms limit for each sensor updates.

If you need an update interval less than 200ms, you should:

  • add android.permission.HIGH_SAMPLING_RATE_SENSORS to app.json permissions field
  • or if you are using bare workflow, add <uses-permission android:name="android.permission.HIGH_SAMPLING_RATE_SENSORS"/> to AndroidManifest.xml.

Set the sensor update interval.

  • Undo-iconvoid

Interfaces

PermissionResponse

An object obtained by permissions get and request functions.

NameTypeDescription
canAskAgainbooleanIndicates if user can be asked again for specific permission. If not, one should be directed to the Settings app in order to enable/disable the permission.
expiresPermissionExpirationDetermines time when the permission expires.
grantedbooleanA convenience boolean that indicates if the permission is granted.
statusPermissionStatusDetermines the status of the permission.

Types

LightSensorMeasurement

NameTypeDescription
illuminancenumberAmbient light level registered by the device measured in lux (lx).

PermissionExpiration

Permission expiration time. Currently, all permissions are granted permanently.

Acceptable values are: 'never', number.

Subscription

NameTypeDescription
remove() => voidA method to unsubscribe the listener.

Enums

PermissionStatus

PermissionStatus.DENIED = "denied"

User has denied the permission.

PermissionStatus.GRANTED = "granted"

User has granted the permission.

PermissionStatus.UNDETERMINED = "undetermined"

User hasn't granted or denied the permission yet.

  • Message-iconAsk a question on the forums about LightSensor
  • Github-iconView open bug reports for LightSensor
  • Code-iconView source code for LightSensor
  • Build-iconView package in npm Registry
  • Edit-iconEdit this page

Was this doc helpful?