tezvyn:

Building a native module from scratch

AI-drafted, machine-checkedSource: interviewadvanced
WHAT IT TESTS

bridging JS to platform APIs.

OUTLINE

write a native module class with exported methods or constants, register it via a package, then expose a typed JS wrapper.

WHAT THIS TESTS It checks that you grasp the native-to-JavaScript boundary: how platform capabilities like battery level get surfaced to React, and the registration plumbing required on each side.

A GOOD ANSWER COVERS On the native Android side you create a module class, for example BatteryModule, extending the React Native module base class. You give it a name via getName, and you expose data either as constants through getConstants or as methods. Methods that read live values should return results asynchronously using a Promise or callback because the call crosses into JavaScript. You then create a ReactPackage, for instance BatteryPackage, that returns your module from createNativeModules, and register that package in the app's MainApplication package list. The iOS side mirrors this with an RCT module exporting methods. On the JavaScript side you read NativeModules.Battery in the legacy architecture, or under the New Architecture you write a codegen spec file describing the TurboModule and let codegen generate the interfaces. You typically wrap the raw module in a small typed JS file so consumers get clean types and a stable API.

COMMON WRONG ANSWERS Confusing a native module, which exposes methods and data, with a native UI component, which renders a view. Returning live values synchronously. Forgetting package registration so the module is undefined at runtime.

LIKELY FOLLOW-UPS How does a TurboModule differ from a legacy native module? On which thread do module methods run, and how do you avoid blocking it? How do you emit events back to JS?

ONE CONCRETE EXAMPLE BatteryModule exposes getBatteryLevel returning a Promise. Android reads the system battery via BatteryManager off the main thread and resolves the promise. You register BatteryPackage in MainApplication, then in batteryModule.ts call NativeModules.Battery.getBatteryLevel(), exporting an async function with a number return type for the rest of the app.

Read the original → reactnative.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.