npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-native-applifecycle

v2.0.0

Published

⚛ Enhances the reliability of managing app lifecycles across iOS and Android platforms, ensuring consistent behavior regarding foreground and background states.

Readme


🚀 Quick Start

# 1. Install dependency
yarn add react-native-applifecycle
# or: npm i -S react-native-applifecycle
import React, { useEffect } from 'react';
import { View, Text } from 'react-native';
import { AppLifecycle, useAppLifecycle } from 'react-native-applifecycle';

export default function App() {
  // Option A: Convenient React Hook
  const currentLifecycle = useAppLifecycle();

  // Option B: Event Subscription
  useEffect(() => {
    const subscription = AppLifecycle.addEventListener('change', (state) => {
      console.log('App lifecycle transitioned to:', state);
    });

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

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Current Lifecycle: {currentLifecycle}</Text>
    </View>
  );
}

💡 Why React-Native App Lifecycle?

  • 🎯 Eliminates False Background Events on Android. Opening a camera preview, an image picker, Google Play billing, biometric prompt, or an OAuth Custom Tab halts the main React Native Activity, causing React Native's built-in AppState to prematurely dispatch background. This library keeps your app in active until the entire application process is obscured.
  • 🤖 Powered by AndroidX ProcessLifecycleOwner. Listens directly to the whole application process lifecycle rather than an isolated Activity lifecycle, ensuring architectural fidelity on Android.
  • 🍏 Seamless iOS Parity. Automatically falls back to React Native's native AppState on iOS, which already treats application-level scenes correctly.
  • 🪝 First-Class React Hook. Includes useAppLifecycle() out of the box so functional components can react to lifecycle changes with zero listener boilerplate.
  • 🔄 100% Drop-in AppState Compatibility. Matches the addEventListener(), currentState, and isAvailable APIs of React Native's standard AppState for effortless migration.
  • 🧪 Built-in Jest Mocking. Includes a dedicated mock helper (react-native-applifecycle/jest/AppLifecycleMock) ready for your automated unit and integration tests.
  • 📦 Zero Extra External JS Dependencies. Ultra-lean codebase with native autolinking support for modern React Native applications.

🧠 How It Works

The Core Problem with Standard AppState

React Native's built-in AppState exhibits platform inconsistency when handling Android activities:

  • On iOS: The background state accurately reflects that the entire application has been suspended or sent to the home screen / app switcher.
  • On Android: React Native's AppState binds to the single ReactActivity. When another Activity within your application launches (such as a photo selector, payment flow, or secondary screen), the React Activity calls onPause(), which causes standard AppState to fire background even though the user is actively engaged inside your application.
┌────────────────────────────────────────────────────────────────────────┐
│                        User Opens Camera Activity                      │
├────────────────────────────────┬───────────────────────────────────────┤
│ Standard RN AppState:          │ ⚠️ Reports "background" (Wrong!)     │
│ react-native-applifecycle:     │ ✅ Remains "active" (Correct!)        │
└────────────────────────────────┴───────────────────────────────────────┘

State Comparison

| Scenario | Standard RN AppState (Android) | react-native-applifecycle (Android) | iOS Behavior | |---|---|---|---| | User is in the React Native screen | active | active | active | | Secondary native Activity opens (Camera, Picker, In-App Webview) | background ⚠️ (Premature) | active ✅ | active | | User presses Home or switches apps | background | background | background | | User returns to the app from Home | active | active | active | | Notification Center / App Switcher open | inactive (iOS only) | active (Android) / inactive (iOS) | inactive |

By using react-native-applifecycle, your background sync routines, timeout locks, session managers, and analytics only trigger when the user actually leaves your application.


📋 Requirements

| Platform / Tool | Supported Version | |---|---| | React Native | >= 0.80.0 (New Architecture & Old Architecture supported) | | Android | minSdkVersion >= 24 (AndroidX Lifecycle supported) |


📦 Installation

1. Add JavaScript Package

Using Yarn:

yarn add react-native-applifecycle

Using npm:

npm i -S react-native-applifecycle

2. Native Linking

  • React Native 0.60+ (Autolinking): Autolinking is configured automatically. No manual react-native link or Gradle modifications are required.
  • iOS: No CocoaPods pod install needed specifically for this package since iOS directly utilizes React Native core's AppState.

💻 Usage

1. Using the React Hook: useAppLifecycle()

The simplest way to consume lifecycle status inside React functional components:

import React from 'react';
import { View, Text } from 'react-native';
import { useAppLifecycle } from 'react-native-applifecycle';

export const StatusScreen = () => {
  const lifecycle = useAppLifecycle();

  return (
    <View style={{ padding: 20 }}>
      <Text>Application State: {lifecycle}</Text>
      {lifecycle === 'active' ? (
        <Text>App is in the foreground!</Text>
      ) : (
        <Text>App is running in the background.</Text>
      )}
    </View>
  );
};

2. Subscribing with addEventListener()

For imperative code, class components, or state stores (Zustand, Redux, MobX):

import { useEffect } from 'react';
import { AppLifecycle } from 'react-native-applifecycle';

export const useAppLifecycleLogger = () => {
  useEffect(() => {
    const subscription = AppLifecycle.addEventListener('change', (nextState) => {
      console.log('App state changed to:', nextState);

      if (nextState === 'background') {
        // Safe to pause sensitive timers or persist state
        console.log('Entire app sent to background.');
      } else if (nextState === 'active') {
        // App has returned to the foreground
        console.log('App returned to active foreground.');
      }
    });

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

3. Synchronous State Inspection: currentState

You can inspect the current app state synchronously without waiting for an event:

import { AppLifecycle } from 'react-native-applifecycle';

function checkCurrentStatus() {
  const state = AppLifecycle.currentState;
  console.log('Current state:', state); // 'active' | 'background' | 'inactive' | 'unknown'
}

4. Availability Check: isAvailable

Verifies whether lifecycle observation is available on the current platform:

import { AppLifecycle } from 'react-native-applifecycle';

if (AppLifecycle.isAvailable) {
  console.log('AppLifecycle module is available and ready');
}

5. Multi-Activity Demonstration

For an interactive example showcasing the difference between AppState and AppLifecycle when opening a second Android Activity, check out the Sample Project.


📚 API Reference

Lifecycle States

| State | Platform | Description | |---|---|---| | active | Android & iOS | The application is running in the foreground. At least one activity is visible to the user. | | background | Android & iOS | The application is running in the background. The user is either on the home screen or inside another app entirely. | | inactive | iOS | The application is transitioning between foreground and background, or is in an inactive state such as viewing the multitasking app switcher, opening Notification Center, or handling an incoming call. | | unknown | Android & iOS | Assigned when an unrecognised native lifecycle event is received. On Android the initial value is AppState.currentState. |

For additional background on iOS states, refer to the React Native AppState documentation.


Events

| Event Type | Handler Signature | Description | |---|---|---| | 'change' | (state: AppStateStatus) => void | Fired when the overall application transitions between active, background, or inactive. | | 'memoryWarning' | () => void | (delegated to React Native AppState, all platforms; availability per RN docs) Emitted when the operating system warns that memory is low. | | 'focus' | () => void | (delegated to React Native AppState, all platforms; availability per RN docs) Emitted when the app window gains focus. | | 'blur' | () => void | (delegated to React Native AppState, all platforms; availability per RN docs) Emitted when the app window loses focus. |


Methods

AppLifecycle.addEventListener()

static addEventListener(
  type: AppStateEvent,
  listener: (state: AppStateStatus) => void,
): EventSubscription;

Sets up an event listener that is invoked whenever the specified lifecycle event occurs. Returns an EventSubscription object containing a .remove() method to cleanly unsubscribe.


Properties

| Property | Type | Description | |---|---|---| | AppLifecycle.currentState | AppStateStatus | Synchronous getter returning the current lifecycle state ('active', 'background', 'inactive', or 'unknown'). | | AppLifecycle.isAvailable | boolean | Synchronous getter indicating whether the lifecycle module is supported and available. |


Hooks

useAppLifecycle()

function useAppLifecycle(): AppStateStatus;

A React hook that returns the current lifecycle status and automatically triggers a component re-render whenever the lifecycle state updates.


🧪 Jest Mock

To run unit tests without requiring native Android or iOS lifecycle bindings, add the provided mock to your jest.setup.js or directly inside your test file:

jest.mock('react-native-applifecycle/dist/AppLifecycle', () =>
  require('react-native-applifecycle/jest/AppLifecycleMock'),
);

⚠️ Limitations

[!NOTE] In development mode, some lifecycle events may not trigger as expected due to how React Native manages backgrounding and hot reloading during Metro development sessions.

For further details and discussion, see Issue #13 (comment).


🤝 Contributing

Contributions, bug reports, and feature proposals are always welcome!

  1. Fork the repository and create your topic branch (git checkout -b feat/my-improvement).
  2. Verify that your TypeScript definitions compile without errors:
    yarn build
  3. Commit your changes:
    git commit -m "Add support for new lifecycle trigger"
  4. Push to your branch and open a descriptive Pull Request.

For questions and suggestions, please open an issue.

Support the Author

If this library helped solve your lifecycle issues, consider supporting the maintainer:


⭐ Star History


📄 License

The MIT License (MIT)

Copyright (c) 2024 Douglas Nassif Roma Junior

See the full license file.


🌐 Author & More Projects