react-native-device-activity

React Native wrapper for Apple's Screen Time, Device Activity, and Family Controls APIs.
⚠️ Important: These APIs require special approval and entitlements from Apple. Request this approval as early as possible in your development process.
Table of Contents
Apple's Screen Time APIs Explained
(See WWDC21 for official details.)
Note: Depending on your use case, you might not need all the APIs hence not all the new bundle identifier and capabilities are required. Below is a quick overview of the APIs available.
FamilyControl API
The FamilyControl API allows your app to access Screen Time data and manage restrictions on apps and websites.
What it does: Provides access to selection and monitoring of app/website usage
Example: Selecting which apps (e.g., Instagram, TikTok) to monitor or block
ShieldConfiguration API
Defines the visual appearance and text shown when users attempt to access blocked content.
What it does: Customizes the blocking screen UI
Example:
const shieldConfig = {
title: "Time for a Break!",
subtitle: "These apps are unavailable until midnight.",
primaryButtonLabel: "OK",
iconSystemName: "moon.stars.fill",
};
ShieldAction API
Defines what happens when users interact with shield buttons.
What it does: Controls behavior when users tap buttons on the shield
Example:
const shieldActions = {
primary: {
behavior: "close", // Just close the shield when OK is tapped
},
};
ActivityMonitor API
Schedules and manages when restrictions should be applied or removed. This is what will activate the shield when your app is killed.
What it does: Monitors device activity against schedules and thresholds
Example:
// Block social media from 7PM to midnight daily
ReactNativeDeviceActivity.startMonitoring(
"evening_block",
{
intervalStart: { hour: 19, minute: 0 },
intervalEnd: { hour: 23, minute: 59 },
repeats: true,
},
[],
);
Installation in managed Expo projects
Install the package:
npm install react-native-device-activity
# or
yarn add react-native-device-activity
Configure the Expo plugin in your app.json or app.config.js:
"plugins": [
[
"expo-build-properties",
{
"ios": {
"deploymentTarget": "15.1"
},
},
],
[
"react-native-device-activity",
{
"appleTeamId": "<YOUR_TEAM_ID>",
"appGroup": "group.<YOUR_APP_GROUP_NAME>"
}
]
],
Generate the native projects:
npx expo prebuild --platform ios
Verify Xcode Targets: After running prebuild, open the ios directory in Xcode (open ios/YourProject.xcworkspace). Check that you have the following targets in addition to your main app target:
ActivityMonitorExtension
ShieldAction
ShieldConfiguration
Some Notes
- It's not possible to 100% know which familyActivitySelection an event being handled is triggered for in the context of the Shield UI/actions. We try to make a best guess here - prioritizing apps/websites in an activitySelection over categories, and smaller activitySelections over larger ones (i.e. "Instagram" over "Instagram + Facebook" over "Social Media Apps"). This means that if you display a shield specific for the Instagram selection that will take precedence over the less specific shields.
- When determining which familyActivitySelectionId that should be used, it will only look for familyActivitySelectionIds that are contained in any of the currently monitored activity names (i.e. if familyActivitySelectionId is "social-media-apps" it will only trigger if there is an activity name that contains "social-media-apps"). This might be a limitation for some implementations, it would probably be nice to make this configurable.
Data model
Almost all the functionality is built around persisting configuration as well as event history to UserDefaults.
- familyActivitySelectionId mapping. This makes it possible for us to tie a familyActivitySelection token to an id that we can reuse and refer to at a later stage.
- Triggers. This includes configuring shield UI/actions as well as sending web requests or notifications from the Swift background side, in the context of the device activity monitor process. Prefixed like actionsfor${goalId} in userDefaults. This is how we do blocking of apps, updates to shield UI/actions etc.
- Event history. Contains information of which events have been triggered and when. Prefixed like events_${goalId} in userDefaults. This can be useful for tracking time spent.
- ShieldIds. To reduce the storage strain on userDefaults shields are referenced with shieldIds.
Installation in bare React Native projects
For bare React Native projects, you must ensure that you have installed and configured the expo package before continuing.
Add the package to your npm dependencies
npm install react-native-device-activity
Configure for iOS
Run npx pod-install after installing the npm package.
Family Controls (distribution) entitlement requires approval from Apple
As early as possible you want to request approval from Apple, since it can take time to get approved.
Note that until you have approval for all bundleIdentifiers you want to use, you are stuck with local development builds in XCode. i.e., you can't even build an Expo Dev Client.
For every base bundleIdentifier you need approval for 4 bundleIdentifiers (when leveraging all native extensions that is, you can potentially just use the Shield-related ones if you have no need to listen to the events, or similarly just use the ActivityMonitor if you do not need control over the Shield UI):
com.your-bundleIdentifier
com.your-bundleIdentifier.ActivityMonitor
com.your-bundleIdentifier.ShieldAction
com.your-bundleIdentifier.ShieldConfiguration
⚠️ You need to fill out the Apple request form once for each of these bundle identifiers — that means filling out the form 4 separate times (one per bundle identifier listed above) if you are using all native extensions.
Once you've gotten approval you need to manually add the "Family Controls (Distribution)" under Additional Capabilities for each of the bundleIdentifiers on developer.apple.com mentioned above. If you use Expo/EAS this has to be done only once, and after that provisioning will be handled automatically.
⚠️ If you don't do all the above, you will run into a lot of strange provisioning errors.
Basic Example: Event Tracking Approach
Here's another example that focuses on tracking app usage with time thresholds:
import * as ReactNativeDeviceActivity from "react-native-device-activity";
ReactNativeDeviceActivity.revokeAuthorization();
Select Apps to track
For most use cases you need to get an activitySelection from the user, which is a token representing the apps the user wants to track, block or whitelist. This can be done by presenting the native DeviceActivitySelectionView.
Presentation options
The picker now has dedicated components for each presentation style:
*SelectionView components take a raw familyActivitySelection token.
*SelectionViewPersisted components take a familyActivitySelectionId and persist/read the token on the native side by ID.
Native sheet -- DeviceActivitySelectionSheetView (and persisted variant) uses Apple's .familyActivityPicker(isPresented:selection:) flow with native Cancel/Done controls.
// The sheet view acts as an invisible anchor.
// The native side presents the iOS sheet and fires onDismissRequest on Cancel/Done.
{pickerVisible && (
<DeviceActivitySelectionSheetView
style={{ width: 1, height: 1, position: "absolute" }}
onDismissRequest={() => setPickerVisible(false)}
onSelectionChange={handleSelectionChange}
familyActivitySelection={familyActivitySelection}
/>
)}
Custom presentation (fallback/customizable) -- DeviceActivitySelectionView (and persisted variant) renders inline. You can embed it directly in your layout or wrap it in a React Native <Modal> for a custom sheet.
import { Modal, View } from "react-native";
<Modal
visible={visible}
animationType="slide"
presentationStyle="pageSheet"
onRequestClose={onDismiss}
onDismiss={onDismiss}
>
<View style={{ flex: 1 }}>
<DeviceActivitySelectionView
style={{ flex: 1, width: "100%" }}
onSelectionChange={handleSelectionChange}
familyActivitySelection={familyActivitySelection}
/>
</View>
</Modal>
Which one should I use?
- Use
DeviceActivitySelectionSheetView for a native iOS sheet UX (system Cancel/Done).
- Use
DeviceActivitySelectionView when you need full control over presentation and a custom crash fallback UI.
- Use the persisted variants when you want to store/reuse selections across screens/sessions or avoid passing very large selection tokens through JS.
Full example
import * as ReactNativeDeviceActivity from "react-native-device-activity";
const DeviceActivityPicker = () => {
// First things first, you need to request authorization
useEffect(() => {
ReactNativeDeviceActivity.requestAuthorization()
}, [])
const [familyActivitySelection, setFamilyActivitySelection] = React.useState(null);
// next you need to present a native view to let the user select which activities to track, you need to do this before you can start tracking (this is a completely unstyled clickable native view):
return (
<ReactNativeDeviceActivity.DeviceActivitySelectionView
onSelectionChange={(event) => {
setFamilyActivitySelection(
event.nativeEvent.familyActivitySelection
)
}}
familyActivitySelection={familyActivitySelection} />
)
}
}
Some things worth noting here:
- This is a SwiftUI view, which is prone to crashing, especially when browsing larger categories of apps or searching for apps. It's recommended to provide a fallback view (positioned behind the SwiftUI view) that allows the user to know what's happening and reload the view and tailor that to your app's design and UX.
- The activitySelection tokens can be particularly large (especially if you use includeEntireCategory flag), so you probably want to reference them through a familyActivitySelectionId instead of always passing the string token around. Most functions in this library accept a familyActivitySelectionId as well as the familyActivitySelection token directly.
Time tracking
It's worth noting that the Screen Time API is not designed for time tracking out-of-the-box. So you have to set up events with names you can parse as time after they've triggered.