Back to Home

react-native-accelerometer

by Isaías Chávez

A lightweight and modern accelerometer module for React Native, built with the New Architecture (TurboModules + Fabric). Provides real-time access to device acceleration data with high performance, low overhead, and a clean, predictable API.

Features

  • 🚀 Built with New Architecture (TurboModules + Fabric)
  • 📱 Cross-platform support (iOS & Android)
  • High performance with real-time sensor data
  • 🎛️ Configurable filters (low-pass, high-pass, gravity)
  • 🔄 Event-driven updates with customizable intervals
  • 🎯 TypeScript support with full type definitions
  • 🔋 Battery efficient with automatic lifecycle management

Installation

npm install react-native-accelerometer

or with Yarn:

yarn add react-native-accelerometer

iOS Setup

After installing the package, navigate to the iOS folder and install the pods:

cd ios && pod install && cd ..

Or if you're in the root directory:

npx pod-install

Android Setup

No additional setup required. The package uses autolinking.

Usage

Basic Example

import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
import * as Accelerometer from 'react-native-accelerometer';

function App() {
  const [data, setData] = useState({ x: 0, y: 0, z: 0 });

  useEffect(() => {
    // Check if accelerometer is available
    const checkSensor = async () => {
      const available = await Accelerometer.isAvailable();
      console.log('Accelerometer available:', available);
    };

    checkSensor();

    // Set update interval to 100ms
    Accelerometer.setUpdateInterval(100);

    // Start listening to accelerometer updates
    Accelerometer.startUpdates();

    // Subscribe to updates
    const subscription = Accelerometer.addListener((accelerometerData) => {
      setData(accelerometerData);
    });

    // Cleanup
    return () => {
      subscription.remove();
      Accelerometer.stopUpdates();
    };
  }, []);

  return (
    <View>
      <Text>X: {data.x.toFixed(4)}</Text>
      <Text>Y: {data.y.toFixed(4)}</Text>
      <Text>Z: {data.z.toFixed(4)}</Text>
    </View>
  );
}

API Reference

Methods

isAvailable(): Promise<boolean>

Checks if the accelerometer sensor is available on the device.

Returns: Promise that resolves to true if available, false otherwise.

Example:

const available = await Accelerometer.isAvailable();
if (available) {
  console.log('Accelerometer is ready to use');
}

startUpdates(): void

Starts receiving accelerometer updates. Events will be emitted at the configured interval.

Example:

Accelerometer.startUpdates();

stopUpdates(): void

Stops receiving accelerometer updates and unregisters the sensor listener.

Example:

Accelerometer.stopUpdates();

setUpdateInterval(intervalMs: number): void

Sets the interval (in milliseconds) at which accelerometer updates are received.

Parameters:

  • intervalMs - Update interval in milliseconds (e.g., 100 for 10 updates per second)

Example:

// Update every 50ms (20 times per second)
Accelerometer.setUpdateInterval(50);

getCurrentAcceleration(): Promise<AccelerometerData>

Gets the current acceleration data as a one-time reading.

Returns: Promise that resolves to an AccelerometerData object.

Example:

const data = await Accelerometer.getCurrentAcceleration();
console.log(`X: ${data.x}, Y: ${data.y}, Z: ${data.z}`);

setGravityFilter(enabled: boolean): void

Enables or disables gravity filtering. When enabled, attempts to remove the gravity component from acceleration data.

Parameters:

  • enabled - true to enable gravity filtering, false to disable

Example:

// Remove gravity from readings
Accelerometer.setGravityFilter(true);

Note: iOS removes approximately 1.0 G from the Z-axis, while Android removes approximately 9.81 m/s² from the Z-axis.


setLowPassFilter(value: number): void

Sets the low-pass filter coefficient. Low-pass filters smooth out rapid changes, useful for removing noise.

Parameters:

  • value - Filter coefficient between 0.0 and 1.0
    • 0.0 = No filtering (raw data)
    • 1.0 = Maximum smoothing

Example:

// Apply moderate smoothing
Accelerometer.setLowPassFilter(0.5);

setHighPassFilter(value: number): void

Sets the high-pass filter coefficient. High-pass filters remove slow changes, useful for detecting quick movements.

Parameters:

  • value - Filter coefficient between 0.0 and 1.0
    • 0.0 = No filtering
    • 1.0 = Maximum filtering of slow changes

Example:

// Filter out slow movements
Accelerometer.setHighPassFilter(0.5);

addListener(callback): Subscription

Subscribes to accelerometer updates.

Parameters:

  • callback - Function called when new data is available

Returns: Subscription object with a remove() method

Example:

const subscription = Accelerometer.addListener((data) => {
  console.log('Acceleration:', data);
});

// Later, to unsubscribe:
subscription.remove();

removeAllListeners(): void

Removes all active listeners.

Example:

Accelerometer.removeAllListeners();

Types

AccelerometerData

interface AccelerometerData {
  x: number;        // Acceleration on X-axis
  y: number;        // Acceleration on Y-axis
  z: number;        // Acceleration on Z-axis
  timestamp: number; // Timestamp in milliseconds
}

Coordinate System:

  • X-axis: Horizontal (left/right)
  • Y-axis: Vertical (up/down)
  • Z-axis: Depth (forward/backward)

Advanced Examples

With Filters

import * as Accelerometer from 'react-native-accelerometer';

// Configure filters
Accelerometer.setUpdateInterval(50); // 20 updates/second
Accelerometer.setGravityFilter(true); // Remove gravity
Accelerometer.setLowPassFilter(0.3); // Smooth data

// Start listening
Accelerometer.startUpdates();
const subscription = Accelerometer.addListener((data) => {
  console.log('Filtered acceleration:', data);
});

Shake Detection

import * as Accelerometer from 'react-native-accelerometer';

const SHAKE_THRESHOLD = 2.5;

Accelerometer.setUpdateInterval(100);
Accelerometer.startUpdates();

const subscription = Accelerometer.addListener((data) => {
  const { x, y, z } = data;
  const acceleration = Math.sqrt(x * x + y * y + z * z);

  if (acceleration > SHAKE_THRESHOLD) {
    console.log('Device shaken!');
  }
});

Motion-Based Game Control

import * as Accelerometer from 'react-native-accelerometer';

Accelerometer.setUpdateInterval(16); // ~60fps
Accelerometer.setGravityFilter(true);
Accelerometer.setLowPassFilter(0.5);

Accelerometer.startUpdates();
const subscription = Accelerometer.addListener((data) => {
  // Use data.x and data.y to control game character
  moveCharacter(data.x * 10, data.y * 10);
});

Troubleshooting

iOS: Linker Errors

If you encounter linker errors related to CoreMotion, make sure you've run:

cd ios && pod install

Android: Sensor Not Working

Make sure your device has an accelerometer. You can check with:

const available = await Accelerometer.isAvailable();

High Battery Usage

If you're experiencing high battery usage:

  • Increase the update interval: setUpdateInterval(200) or higher
  • Stop updates when not needed: stopUpdates()
  • The module automatically stops sensors when the app goes to background (Android)

Architecture

This package is built with React Native's New Architecture:

  • TurboModules: For high-performance native method calls
  • Fabric: For optimized rendering (if applicable)
  • Codegen: Automatic native code generation from TypeScript specs

Platform-Specific Implementation

  • iOS: Uses CoreMotion framework with CMMotionManager
  • Android: Uses SensorManager with Sensor.TYPE_ACCELEROMETER

License

MIT © Isaías Chávez Martínez


Made with create-react-native-library