How does react native work

React Native as most of us know, is an open source UI library developed by meta to create cross platform applications using Javascript('React' to be precise).

React Native creates truly native apps. Way it does is quite interesting:

The core React Native components are mapped directly to the native UI building blocks:

So RN components as shown above are mapped to the corresponding Native Elements.

It is awesome that we can write our code using 'React', which is a 'javascript' library and the end product we get is a native app. How does this conversion take place? Is Javascript compiled to Native code?

First of all, Javascript can't be compiled to the native code because of the reason that Javascript is dynamically typed language, while C/C++ or Java i.e. Native languages are statically typed.

So if Javascript is not compiled to the Native code, how exactly are the 'React Native Components' mapped to the 'Native ones'. To understand this concept you need to understand how threading model of React Native works:

Threading Model

When we run a React Native project with either:

sh
react-native run-android
react-native run-ios

A packager is run, which bundles all of your code into a single file known as:
main.bundle.js

When we click on the app icon, a main thread is spawned. The 'main thread', looks for entry inside the ios or the android folder in your project.
The 'main thread' opens up 'JavaScript Virtual Machine or JS Thread'.

All of our JS Code then runs on our JS Thread.

Still how do they communicate?

They communicate using 'RN Bridge'.

React Native Bridge

The bridge is the concept that provides a way for bi-directional and asynchronous communications between Native and Javascript Realm.

The React native bridge is built using C/C++ and can be run on the multiple platforms. It embeds Apple JavascriptCore framework, which lets us access JS core VM functionality.

This basically means that JS code can be run inside C/C++ program injecting functions and variables