In this lesson, you will learn how to keep the data living inside your native code in sync with your React Native component state.
The Source of Truth Problem
When you build a Native Module—like a battery manager or a file uploader—that module often holds its own internal state. For example, a "Location Tracker" module might constantly update its internal variable with the user's current coordinates.
The challenge is that your React component (written in JavaScript) is unaware of these hidden changes. If the native module updates its state, the React UI won't re-render because it’s "out of the loop." To bridge this gap, we must establish a two-way communication channel: one for the module to push updates, and one for React to hold the synchronized copy.
Keeping State in Sync
To maintain consistency, we use an Event Emitter. Instead of the JavaScript side constantly asking the native side for data (polling), the native module should "emit" an event whenever its internal state changes. Your React component listens for this event and updates its local useState hook accordingly.
Here is a simplified illustration of how this pattern looks in your component:
import { useEffect, useState } from 'react';
import { NativeEventEmitter, NativeModules } from 'react-native';
const MyModule = NativeModules.MyNativeModule;
const eventEmitter = new NativeEventEmitter(MyModule);
function TrackerComponent() {
const [data, setData] = useState(null);
useEffect(() => {
// 1. Listen for the native update
const subscription = eventEmitter.addListener('onDataChanged', (newData) => {
// 2. Synchronize React state with native state
setData(newData);
});
// Clean up when the component unmounts
return () => subscription.remove();
}, []);
return <Text>Current Native State: {data}</Text>;
}
By subscribing to native events, your React component becomes a "reflective" UI. It doesn't need to own the native state; it simply observes it. When the native side triggers that event, your state setter updates, triggering a re-render to display the fresh data. This keeps the data flow predictable and prevents the UI from showing stale information.
Key Takeaway: To maintain data consistency, treat your native module as the source of truth and use an Event Emitter to push state changes to React, ensuring your component state always reflects the native reality.