<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by codeherence on Medium]]></title>
        <description><![CDATA[Stories by codeherence on Medium]]></description>
        <link>https://medium.com/@codeherence?source=rss-a30cfac5ee5b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JiccKXzpF21xL01eQopcGQ.png</url>
            <title>Stories by codeherence on Medium</title>
            <link>https://medium.com/@codeherence?source=rss-a30cfac5ee5b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 03:52:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@codeherence/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a React Native C++ Turbo Native Module — Part 1]]></title>
            <link>https://codeherence.medium.com/building-a-react-native-c-turbo-native-module-part-1-908afd03c0f8?source=rss-a30cfac5ee5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/908afd03c0f8</guid>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[codeherence]]></dc:creator>
            <pubDate>Wed, 26 Apr 2023 01:52:11 GMT</pubDate>
            <atom:updated>2023-04-26T01:55:30.658Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a React Native C++ Turbo Native Module — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qEplUK8EsK4K7cNfyAe7jA.png" /></figure><p>Over the past few weeks, I have been exploring C++ Turbo Native Modules and becoming comfortable with the C++ ecosystem. Enabling developers to write cross-platform C++ code for iOS and Android has significantly improved performance in the React Native landscape. Unfortunately, the documentation for getting started with C++ Turbo Native Modules is incomplete, lacking crucial information on accessing the runtime, registering functions globally in the new architecture, and more.</p><p>In this post, we will explore how to create our own C++ Turbo Native Module. Specifically, we will be building a library that enables us to extract metadata from a PNG image using the <a href="http://www.libpng.org/pub/png/libpng.html">libpng</a> library in C++.</p><p>Throughout this process, we will learn how to create a new React Native library, add an external dependency (libpng in this case), access the JavaScript Interface (JSI), register our functions on the global runtime, and integrate our C++ implementation within our React Native application.</p><h3>Setup</h3><p>First, we begin by creating a new libary using <a href="https://github.com/callstack/react-native-builder-bob">react-native-builder-bob</a>:</p><pre>npx create-react-native-library@latest react-native-image-metadata</pre><p>Continue with the prompts like so until you reach the list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*jtRjsKJZoXakrqklOqtjvA.png" /></figure><p>and choose the <strong>Turbo Module</strong> option. Then from this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*IBdcxMW1xN4bOGDuAA-sBw.png" /></figure><p>choose the <strong>C++ for Android &amp; iOS</strong> option.</p><p>Now, we have set up a new Turbo Module that uses C++. If you want to review the trivial example that the scaffolding library provided, check out the cpp folder and how the implementation is used in ios/ImageMetadata.mm .</p><p>Now, we can simply run</p><pre>yarn</pre><p>in the root folder to install all dependencies in the root project and example folder.</p><h3>iOS</h3><p>We will begin by setting up the iOS implementation so that it provides the JSI runtime to our C++ code, so that we can register our C++ functions globally.</p><h4>Replace ImageMetadata.h</h4><p>We replace the <strong>ios/ImageMetadata.h</strong> file with the following:</p><pre>#import &lt;React/RCTBridgeModule.h&gt;<br><br>@interface ImageMetadata : NSObject &lt;RCTBridgeModule&gt;<br><br>@property(nonatomic, assign) BOOL setBridgeOnMainQueue;<br><br>@end</pre><p>and its neighbouring <strong>ImageMetadata.mm</strong> file with:</p><pre>#import &quot;ImageMetadata.h&quot;<br><br>#import &lt;React/RCTBridge+Private.h&gt;<br><br>#import &lt;React/RCTUtils.h&gt;<br>#import &lt;ReactCommon/RCTTurboModule.h&gt;<br>#import &lt;jsi/jsi.h&gt;<br><br>#import &quot;../cpp/bindings.h&quot;<br><br>@implementation ImageMetadata<br><br>RCT_EXPORT_MODULE(IMD)<br><br>RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(install) {<br>  NSLog(@&quot;Installing ImageMetadata module...&quot;);<br><br>  RCTBridge *bridge = [RCTBridge currentBridge];<br>  RCTCxxBridge *cxxBridge = (RCTCxxBridge *)bridge;<br>  if (cxxBridge == nil) {<br>    return @false;<br>  }<br><br>  using namespace facebook;<br><br>  auto jsiRuntime = (jsi::Runtime *)cxxBridge.runtime;<br>  if (jsiRuntime == nil) {<br>    return @false;<br>  }<br>  auto &amp;runtime = *jsiRuntime;<br><br>  imd::install(runtime);<br><br>  return @true;<br>}<br><br>@end</pre><p>There are a few things that are going on in the code above:</p><ul><li>We exported a module IMD, which will be used in our JavaScript later.</li><li>We exported a blocking synchronous function install which will retrieve a reference to the JSI runtime and supply it to our C++ code so that it can install our C++ functions.</li><li>We imported a bindings.h file, which doesn’t exist yet, that will install all of our C++ functions against the global runtime.</li></ul><p>Now, let’s go back to our cpp folder. We should see 2 files: <strong>react-native-image-metadata.cpp</strong> and <strong>react-native-image-metadata.h</strong>. Let’s delete both of these and create the following 2 files:</p><ul><li><strong>bindings.h</strong></li><li><strong>bindings.cpp</strong></li></ul><h4>bindings.h</h4><p>In this file, we will create a namespace imd and define the install function that will take the JSI runtime:</p><pre>#include &lt;jsi/jsi.h&gt;<br>#include &lt;jsi/jsilib.h&gt;<br><br>namespace jsi = facebook::jsi;<br><br>namespace imd {<br>void install(jsi::Runtime&amp; rt);<br>}</pre><h4>bindings.cpp</h4><p>In this file, we will implement the install function for the imd namespace:</p><pre>#include &quot;bindings.h&quot;<br><br>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br><br>using namespace facebook;<br><br>void imd::install(jsi::Runtime&amp; rt) {<br>  auto getImageMetadata = jsi::Function::createFromHostFunction(rt, <br>                                                                jsi::PropNameID::forAscii(rt, &quot;getImageMetadata&quot;), <br>                                                                1,<br>                                                                [](jsi::Runtime&amp; rt, <br>                                                                   const jsi::Value&amp; thisVal, <br>                                                                   const jsi::Value* args, <br>                                                                   size_t count) -&gt; jsi::Object <br>                                                                {<br>                                                                  if (count == 0) {<br>                                                                    throw jsi::JSError(rt,<br>                                                                                       &quot;[react-native-image-metadata][&quot;<br>                                                                                       &quot;getImageMetadata] file path is required&quot;);<br>                                                                  }<br><br>                                                                  if (!args[0].isString()) {<br>                                                                    throw jsi::JSError(rt,<br>                                                                                       &quot;[react-native-image-metadata][getImageMetadata] &quot;<br>                                                                                       &quot;file path must be a string&quot;);<br>                                                                  }<br><br>                                                                  std::string path = args[0].asString(rt).utf8(rt);<br><br>                                                                  jsi::Object result(rt);<br><br>                                                                  result.setProperty(rt, &quot;width&quot;, 100);<br>                                                                  result.setProperty(rt, &quot;height&quot;, 100);<br><br>                                                                  return result;<br>                                                                });<br><br>  jsi::Object md = jsi::Object(rt);<br><br>  md.setProperty(rt, &quot;getImageMetadata&quot;, std::move(getImageMetadata));<br><br>  rt.global().setProperty(rt, &quot;__IMDProxy&quot;, std::move(md));<br>}</pre><p>A lot is going on here, but the gist of it is that:</p><ul><li>we are creating a JSI function with the name getImageMetadata</li><li>which receives 1 argument (our file path)</li><li>that will execute the lambda function that is supplied as the 4th argument to createFromHostFunction</li></ul><p>Keep in mind that the current iteration of the function only returns the following object:</p><pre>{<br>  width: 100,<br>  height: 100<br>}</pre><p>After that, we create an object md and declare it the owner of the function reference, and lastly, register the md object on the global runtime under the name __IMDProxy, and declare __IMDProxy the owner of it. We use move semantics to ensure that the reference is not garbage collected, since it is still owned by the runtime as the application runs.</p><p>For more information on move semantics in C++, feel free to reference the <a href="https://en.cppreference.com/w/cpp/utility/move">std::move documentation</a>.</p><h4>Modify the root src folder</h4><p>Let’s quickly clean up the src folder in the root directory.</p><p>First, we replace <strong>index.tsx</strong> with:</p><pre>export const getImageMetadata = (path: string) =&gt; {<br>  console.log(path);<br><br>  return {<br>    width: 100,<br>    height: 100,<br>  };<br>};</pre><p>Then, we remove all the code in the NativeImageMetadata.ts file.</p><p>Lastly, we slightly modify App.tsx in the example application by removing the reference to the old multiply function:</p><pre>import * as React from &#39;react&#39;;<br>import { StyleSheet, View, Text } from &#39;react-native&#39;;<br>import { getImageMetadata } from &#39;react-native-image-metadata&#39;;<br><br>const meta = getImageMetadata(&#39;some_img.png&#39;);<br><br>export default function App() {<br>  return (<br>    &lt;View style={styles.container}&gt;<br>      &lt;Text&gt;Result: {JSON.stringify(meta)}&lt;/Text&gt;<br>    &lt;/View&gt;<br>  );<br>}<br><br>const styles = StyleSheet.create({<br>  container: {<br>    flex: 1,<br>    alignItems: &#39;center&#39;,<br>    justifyContent: &#39;center&#39;,<br>  },<br>  box: {<br>    width: 60,<br>    height: 60,<br>    marginVertical: 20,<br>  },<br>});</pre><h4>Pause</h4><p>Let’s try running our application to see if everything is still working. Before we run it, we need to ensure that our example application is using the podspec we defined in our root folder as a reference:</p><ol><li>Go to example/ios/Podfile file</li><li>After the `use_react_native` call, add the line below:</li></ol><pre>use_react_native!(<br>  ...<br>)<br><br>pod &#39;react-native-image-metadata&#39;, :path =&gt; &#39;../..&#39; # &lt;-- Add this line</pre><p>3. Run the following:</p><pre>cd example/ios &amp;&amp; bundle install &amp;&amp; RCT_NEW_ARCH_ENABLED=1 bundle exec pod install</pre><p>After this, we can run the application on iOS by opening 2 terminals and running the following in each:</p><pre>yarn start</pre><p>and</p><pre>yarn run ios</pre><p>We should notice that the application is running, so we haven’t broken anything yet on iOS.</p><h3>JavaScript</h3><p>Now that we have set up iOS and implemented the C++ module, we need to ensure that JavaScript calls the install function when our application uses the react-native-image-metadata dependency.</p><p>We will now write our module initialization in the src/NativeImageMetadata.ts file, which should be empty now.</p><p>Add the following code to NativeImageMetadata.ts:</p><pre>import { NativeModules } from &#39;react-native&#39;;<br><br>declare global {<br>  function nativeCallSyncHook(): unknown;<br>  var __IMDProxy: object | undefined;<br>}<br><br>if (global.__IMDProxy == null) {<br>  const IMDModule = NativeModules.IMD;<br><br>  if (IMDModule == null) {<br>    throw new Error(<br>      &#39;Base react-native-image-metadata module not found. Maybe try rebuilding the app.&#39;<br>    );<br>  }<br><br>  // Check if we are running on-device (JSI)<br>  if (global.nativeCallSyncHook == null || IMDModule.install == null) {<br>    throw new Error(<br>      &#39;Failed to install react-native-image-metadata: React Native is not running on-device. ImageMetadata can only be used when synchronous method invocations (JSI) are possible. If you are using a remote debugger (e.g. Chrome), switch to an on-device debugger (e.g. Flipper) instead.&#39;<br>    );<br>  }<br><br>  // Call the synchronous blocking install() function<br>  const result = IMDModule.install();<br>  if (result !== true) {<br>    throw new Error(<br>      `Failed to install react-native-image-metadata: The native ImageMetadata Module could not be installed! Looks like something went wrong when installing JSI bindings: ${result}`<br>    );<br>  }<br><br>  // Check again if the constructor now exists. If not, throw an error.<br>  if (global.__IMDProxy == null) {<br>    throw new Error(<br>      &#39;Failed to install react-native-image-metadata, the native initializer function does not exist. Are you trying to use ImageMetadata from different JS Runtimes?&#39;<br>    );<br>  }<br>}<br><br>interface IIMD {<br>  getImageMetadata: (filePath: string) =&gt; ImageMetadata;<br>}<br><br>const proxy = global.__IMDProxy;<br>export const IMD = proxy as IIMD;<br><br>export type ImageMetadata = {<br>  /** The width of the image. */<br>  width: number;<br>  /** The height of the image. */<br>  height: number;<br>};</pre><p>The code above initializes the module if it hasn’t done so already, and calls the native install function we created in the <strong>ios/ImageMetadata.mm</strong> file. After the module is installed, we export the proxy object under the variable <strong>IMD</strong>.</p><p>Now, let’s test out our Turbo Module function by modifying the src/index.ts file’s getImageMetadata function to use the IMD proxy we exported above:</p><pre>import { IMD } from &#39;./NativeImageMetadata&#39;;<br>import type { ImageMetadata } from &#39;./NativeImageMetadata&#39;;<br><br>export const getImageMetadata = (path: string): ImageMetadata =&gt; {<br>  return IMD.getImageMetadata(path);<br>};<br><br>export type { ImageMetadata };</pre><p>If you run the example application again, you will see that it will still show the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HaKPlPIvy6nPCsafzM1mTA.png" /></figure><p>Awesome! We have successfully linked our C++ code to JavaScript and used our module to return the result of our C++ lambda function.</p><h3>Using libpng to extract PNG metadata</h3><p>Now that everything is linked, we can focus on the C++ code and extend it to use libpng to read the PNG, extract its metadata, and return it to our application.</p><h4>Install libpng on iOS</h4><p>First, we begin by adding libpng as a dependency in our podspec file. Since Cocoapods already distributes a version of <a href="https://cocoapods.org/pods/libpng">libpng for iOS</a>, we can add the following line to our react-native-image-metadata.podspec file:</p><pre>s.dependency &quot;libpng&quot;, &quot;~&gt; 1.6.35&quot;</pre><p>Our podspec file should look like this:</p><pre>require &quot;json&quot;<br><br>package = JSON.parse(File.read(File.join(__dir__, &quot;package.json&quot;)))<br>folly_compiler_flags = &#39;-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1 -Wno-comma -Wno-shorten-64-to-32&#39;<br><br>Pod::Spec.new do |s|<br>  s.name         = &quot;react-native-image-metadata&quot;<br>  s.version      = package[&quot;version&quot;]<br>  s.summary      = package[&quot;description&quot;]<br>  s.homepage     = package[&quot;homepage&quot;]<br>  s.license      = package[&quot;license&quot;]<br>  s.authors      = package[&quot;author&quot;]<br><br>  s.platforms    = { :ios =&gt; &quot;11.0&quot; }<br>  s.source       = { :git =&gt; &quot;https://github.com/e-younan/react-native-image-metadata.git&quot;, :tag =&gt; &quot;#{s.version}&quot; }<br><br>  s.source_files = &quot;ios/**/*.{h,m,mm}&quot;, &quot;cpp/**/*.{h,cpp}&quot;<br><br>  s.dependency &quot;React-Core&quot;<br>  s.dependency &quot;libpng&quot;, &quot;~&gt; 1.6.35&quot;<br><br>  # Don&#39;t install the dependencies when we run `pod install` in the old architecture.<br>  if ENV[&#39;RCT_NEW_ARCH_ENABLED&#39;] == &#39;1&#39; then<br>    s.compiler_flags = folly_compiler_flags + &quot; -DRCT_NEW_ARCH_ENABLED=1&quot;<br>    s.pod_target_xcconfig    = {<br>        &quot;HEADER_SEARCH_PATHS&quot; =&gt; &quot;\&quot;$(PODS_ROOT)/boost\&quot;&quot;,<br>        &quot;OTHER_CPLUSPLUSFLAGS&quot; =&gt; &quot;-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1&quot;,<br>        &quot;CLANG_CXX_LANGUAGE_STANDARD&quot; =&gt; &quot;c++17&quot;<br>    }<br>    s.dependency &quot;React-Codegen&quot;<br>    s.dependency &quot;RCT-Folly&quot;<br>    s.dependency &quot;RCTRequired&quot;<br>    s.dependency &quot;RCTTypeSafety&quot;<br>    s.dependency &quot;ReactCommon/turbomodule/core&quot;<br>  end<br>end</pre><p>Then, let’s install the pod dependencies in our example application to ensure that libpng is installed:</p><pre>cd example/ios &amp;&amp; RCT_NEW_ARCH_ENABLED=1 bundle exec pod install</pre><p>After running the command above, you should see the following 2 green lines in the terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*VySrm6O-QmxY9w0qcCDHAQ.png" /></figure><p>Great! We have successfully added libpng as a dependency to our module.</p><h4>C++ Implementation</h4><p>Let’s begin by creating 2 files in the cpp folder: metadata.h and metadata.cpp.</p><h4>metadata.h</h4><p>In the metadata.h file, we add the following:</p><pre>#include &lt;jsi/jsi.h&gt;<br><br>#include &lt;fstream&gt;<br>#include &lt;string&gt;<br><br>namespace jsi = facebook::jsi;<br><br>/**<br> * A deleter for std::ifstream that closes the file before deleting it.<br> */<br>struct FileStreamDeleter {<br>  void operator()(std::ifstream* file) const {<br>    file-&gt;close();<br>    delete file;<br>  }<br>};<br><br>bool isFilePNG(const std::string&amp; path);<br><br>double getFileSize(const std::string&amp; path);<br><br>jsi::Object getPNGMetadata(jsi::Runtime&amp; rt, const std::string&amp; path);</pre><p>We define the following in our header file:</p><ul><li><strong>FileStreamDeleter</strong> — A deleter for <strong>std::ifstream</strong>’s that closes the file before deleting it. This will be used in conjunction with smart pointers in order to ensure that ifstream’s are cleaned up when the function is finished.</li><li><strong>isFilePNG</strong> — returns true if the file path hosts a PNG image</li><li><strong>getFileSize</strong> — a function that returns the size of the file</li><li><strong>getPNGMetadata</strong> — retrieve the PNG’s metadata and return a JSI Object to the caller</li></ul><h4>metadata.cpp</h4><p>In the implementation file, we write the extraction logic using libpng:</p><pre>#include &quot;metadata.h&quot;<br><br>#include &lt;jsi/jsi.h&gt;<br><br>#include &lt;fstream&gt;<br>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br>#include &lt;vector&gt;<br><br>#include &quot;png.h&quot;<br><br>namespace jsi = facebook::jsi;<br><br>void pngReadCallback(png_structp pngPtr, png_bytep data, png_size_t length) {<br>  auto input = reinterpret_cast&lt;std::istream*&gt;(png_get_io_ptr(pngPtr));<br>  input-&gt;read(reinterpret_cast&lt;char*&gt;(data), length);<br>}<br><br>bool isFilePNG(const std::string&amp; path) {<br>  std::unique_ptr&lt;std::ifstream, FileStreamDeleter&gt; fileStream(new std::ifstream(path, std::ios::in | std::ios::binary));<br>  if (!fileStream || !fileStream-&gt;is_open()) {<br>    return false;<br>  }<br><br>  // Read the first 8 bytes of the file<br>  std::vector&lt;unsigned char&gt; header(8);<br>  fileStream-&gt;read((char*)header.data(), header.size());<br><br>  // All pngs begin with the following 8 bytes: 0x89 0x50 0x4E 0x47 0x0D 0x0A 0x1A 0x0A<br>  const std::vector&lt;unsigned char&gt; pngMagic = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};<br><br>  // Check if the file matches the PNG magic number<br>  if (std::equal(header.begin(), header.end(), pngMagic.begin())) {<br>    return true;<br>  }<br><br>  return false;<br>}<br><br>double getFileSize(const std::string&amp; path) {<br>  std::unique_ptr&lt;std::ifstream, FileStreamDeleter&gt; inputFile(new std::ifstream(path, std::ios::in | std::ios::binary));<br>  inputFile-&gt;seekg(0, std::ios::end);<br>  std::streamsize fileSize = inputFile-&gt;tellg();<br>  inputFile-&gt;seekg(0, std::ios::beg);<br><br>  return static_cast&lt;double&gt;(fileSize);<br>}<br><br>jsi::Object getPNGMetadata(jsi::Runtime&amp; rt, const std::string&amp; path) {<br>  if (!isFilePNG(path)) {<br>    throw jsi::JSError(rt, &quot;The file is not a PNG.&quot;);<br>  }<br><br>  std::unique_ptr&lt;std::ifstream, FileStreamDeleter&gt; inputFile(new std::ifstream(path, std::ios::in | std::ios::binary));<br>  if (!inputFile || !inputFile-&gt;is_open()) {<br>    throw jsi::JSError(rt, &quot;Failed to open input file at path: &quot; + path);<br>  }<br><br>  // Initialize PNG structures<br>  png_structp pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);<br>  if (!pngPtr) {<br>    throw jsi::JSError(rt, &quot;Failed to create PNG read struct&quot;);<br>  }<br><br>  png_infop infoPtr = png_create_info_struct(pngPtr);<br>  if (!infoPtr) {<br>    png_destroy_read_struct(&amp;pngPtr, nullptr, nullptr);<br>    throw jsi::JSError(rt, &quot;Failed to create PNG info struct&quot;);<br>  }<br><br>  // Set error handling<br>  if (setjmp(png_jmpbuf(pngPtr))) {<br>    png_destroy_read_struct(&amp;pngPtr, &amp;infoPtr, nullptr);<br>    throw jsi::JSError(rt, &quot;Error during PNG metadata retrieval&quot;);<br>  }<br><br>  // Initialize PNG IO<br>  png_set_read_fn(pngPtr, static_cast&lt;void*&gt;(inputFile.get()), pngReadCallback);<br><br>  // Read PNG info<br>  png_read_info(pngPtr, infoPtr);<br><br>  png_uint_32 width, height;<br>  int bitDepth, colorType, interlaceMethod, compressionMethod, filterMethod;<br>  png_get_IHDR(pngPtr, infoPtr, &amp;width, &amp;height, &amp;bitDepth, &amp;colorType, &amp;interlaceMethod, &amp;compressionMethod, &amp;filterMethod);<br><br>  // Clean up<br>  png_destroy_read_struct(&amp;pngPtr, &amp;infoPtr, nullptr);<br><br>  // Get file size<br>  double size = getFileSize(path);<br><br>  // Create an object to dump all our metadata into and return to the original caller.<br>  jsi::Object result(rt);<br><br>  result.setProperty(rt, &quot;width&quot;, static_cast&lt;int&gt;(width));<br>  result.setProperty(rt, &quot;height&quot;, static_cast&lt;int&gt;(height));<br>  result.setProperty(rt, &quot;size&quot;, size);<br>  result.setProperty(rt, &quot;bitDepth&quot;, bitDepth);<br>  result.setProperty(rt, &quot;colorType&quot;, colorType);<br>  result.setProperty(rt, &quot;interlaceMethod&quot;, interlaceMethod);<br>  result.setProperty(rt, &quot;compressionMethod&quot;, compressionMethod);<br>  result.setProperty(rt, &quot;filterMethod&quot;, filterMethod);<br><br>  return result;<br>}</pre><p>Since this isn’t a C++ tutorial, I will not dive deep into the implementation. Let’s use our new getImageMetadata function in our bindings that we defined earlier.</p><p>In bindings.cpp, we make a modification:</p><pre>#include &quot;bindings.h&quot;<br><br>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br><br>#include &quot;metadata.h&quot; // &lt;--- This is the header file we created in the previous step<br><br>using namespace facebook;<br><br>void imd::install(jsi::Runtime&amp; rt) {<br>  auto getImageMetadata = jsi::Function::createFromHostFunction(rt, jsi::PropNameID::forAscii(rt, &quot;getImageMetadata&quot;), 1,<br>                                                                [](jsi::Runtime&amp; rt, const jsi::Value&amp; thisVal, const jsi::Value* args, size_t count) -&gt; jsi::Object {<br>                                                                  if (count == 0) {<br>                                                                    throw jsi::JSError(rt,<br>                                                                                       &quot;[react-native-image-metadata][&quot;<br>                                                                                       &quot;getImageMetadata] file path is required&quot;);<br>                                                                  }<br><br>                                                                  if (!args[0].isString()) {<br>                                                                    throw jsi::JSError(rt,<br>                                                                                       &quot;[react-native-image-metadata][getImageMetadata] &quot;<br>                                                                                       &quot;file path must be a string&quot;);<br>                                                                  }<br><br>                                                                  std::string path = args[0].asString(rt).utf8(rt);<br><br>                                                                  return getPNGMetadata(rt, path); // &lt;--- This is the function we created in the previous step<br>                                                                });<br><br>  jsi::Object md = jsi::Object(rt);<br><br>  md.setProperty(rt, &quot;getImageMetadata&quot;, std::move(getImageMetadata));<br><br>  rt.global().setProperty(rt, &quot;__IMDProxy&quot;, std::move(md));<br>}</pre><p>Now that we have updated our function that is bounded to the JavaScript context, let’s update our TypeScript interface to reflect the changes in our metadata.</p><p>In src/NativeImageMetadata.ts, we update the <strong>ImageMetadata </strong>type with the following updated type:</p><pre><br>export type ImageMetadata = {<br>  /**<br>   * The width of the image.<br>   */<br>  width: number;<br>  /**<br>   * The height of the image.<br>   */<br>  height: number;<br>  /**<br>   * The size of the image in bytes.<br>   */<br>  size: number;<br>  /**<br>   * The bit depth of the image.<br>   */<br>  bitDepth: number;<br>  /**<br>   * The color type of the image.<br>   */<br>  colorType: number;<br>  /**<br>   * The interlace method of the image.<br>   */<br>  interlaceMethod: number;<br>  /**<br>   * The compression method of the image.<br>   */<br>  compressionMethod: number;<br>  /**<br>   * The filter method of the image.<br>   */<br>  filterMethod: number;<br>};</pre><p>And voila, we can use libpng to extract the metadata of a PNG in React Native using C++.</p><h3>Fixing the Example Application</h3><p>Now that we have updated the module to extract the information from a PNG, we need to update App.tsx in our example application with a real PNG image to get it to work.</p><p>If you try to run the application, you’ll see the following error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hnd2OTK46nQ4O7elAy3B4A.png" /></figure><p>Let’s fix the example so that we can choose a PNG from the camera roll using <a href="https://github.com/react-native-image-picker/react-native-image-picker">react-native-image-picker</a>, and get its metadata after.</p><h4>Set up react-native-image-picker</h4><p>In order to set up react-native-image-picker, we execute the following commands:</p><pre>cd example<br>yarn add react-native-image-picker<br>cd ios<br>RCT_NEW_ARCH_ENABLED=1 bundle exec pod install</pre><p>Once the pod dependencies are installed, we can update <strong>App.tsx</strong> with the following to test our module:</p><pre>import React from &#39;react&#39;;<br>import { StyleSheet, View, Text, Pressable, Platform } from &#39;react-native&#39;;<br>import { launchImageLibrary } from &#39;react-native-image-picker&#39;;<br>import { getImageMetadata, ImageMetadata } from &#39;react-native-image-metadata&#39;;<br><br>const App = () =&gt; {<br>  const [metadata, setMetadata] = React.useState&lt;ImageMetadata | null&gt;(null);<br><br>  const selectAndGetMetadata = async () =&gt; {<br>    const result = await launchImageLibrary({<br>      mediaType: &#39;photo&#39;,<br>      selectionLimit: 1,<br>    });<br><br>    if (result.didCancel) return;<br>    if (result.errorCode) return;<br>    if (!result.assets || result.assets.length === 0) return;<br><br>    const asset = result.assets[0];<br>    if (!asset || !asset.uri) return;<br><br>    console.log(&#39;Selected image:&#39;);<br>    console.log(asset);<br><br>    const normalizedUri =<br>      Platform.OS === &#39;ios&#39; ? asset.uri.replace(&#39;file://&#39;, &#39;&#39;) : asset.uri;<br>    console.log(normalizedUri);<br>    try {<br>      const meta = getImageMetadata(normalizedUri);<br>      setMetadata(meta);<br>    } catch (error) {<br>      setMetadata(null);<br>      if (error instanceof Error) {<br>        console.error(error);<br>        console.error(error.message);<br>      }<br>    }<br>  };<br><br>  return (<br>    &lt;View style={styles.container}&gt;<br>      &lt;Pressable onPress={selectAndGetMetadata} style={styles.chooseButton}&gt;<br>        &lt;Text&gt;Choose an image&lt;/Text&gt;<br>      &lt;/Pressable&gt;<br><br>      {metadata &amp;&amp; (<br>        &lt;Text style={styles.metadata}&gt;<br>          Metadata: {JSON.stringify(metadata)}<br>        &lt;/Text&gt;<br>      )}<br>    &lt;/View&gt;<br>  );<br>};<br><br>export default App;<br><br>const styles = StyleSheet.create({<br>  container: {<br>    flex: 1,<br>    backgroundColor: &#39;white&#39;,<br>    alignItems: &#39;center&#39;,<br>    justifyContent: &#39;center&#39;,<br>  },<br>  chooseButton: {<br>    padding: 12,<br>    backgroundColor: &#39;yellow&#39;,<br>  },<br>  metadata: {<br>    marginTop: 12,<br>    paddingHorizontal: 12,<br>    fontSize: 18,<br>  },<br>});</pre><p>And voila, once we run the application on iOS, we should see the following output after choosing a PNG in our camera roll:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D3eUMCFO4aq2BKjjEpOUjw.png" /></figure><h3>Download the Code</h3><p>If you would like to download the code for this medium post, it can be found <a href="https://github.com/e-younan/CxxReactNativeIMDGuide">here</a>.</p><h3>Conclusion</h3><p>The ability to use C++ in our React Native applications unlocks the potential for highly performant modules. C++ is particularly advantageous for use cases such as cryptography, compression, file I/O, streaming, and more — all in a cross-platform implementation that both Android and iOS can accommodate.</p><p>Stay tuned for Part 2, in which we complete the implementation by setting up Android. We will build libpng for all relevant architectures on Android, link it via CMake, and add the necessary code to the cpp-adapter to ensure everything works seamlessly.</p><h4>Get in touch</h4><p>If you or your organization are seeking to develop highly interactive and high-performance cross-platform applications, we invite you to <a href="https://codeherence.com/">connect with us</a> and explore how our expertise can benefit your project.</p><h3>Follow me</h3><p>If you would like to see more content like this, make requests on the type of content you want to see, etc., feel free to:</p><ol><li>Follow <a href="https://twitter.com/e_younan">my Twitter</a></li><li>Join my <a href="https://discord.gg/aseNHjaUQB">Discord</a></li><li>Follow me on <a href="https://www.linkedin.com/in/evan-younan-027160181/">LinkedIn</a></li></ol><p>In the upcoming weeks, I will be working on creating libraries that take advantage of C++ Turbo Modules to improve the performance of specific use cases that are common in React Native applications. Stay tuned!</p><h3>Credits</h3><p>A lot of the implementation and guidance has been extracted from <a href="https://ospfranco.com/post/2021/02/24/how-to-create-a-javascript-jsi-module/">OSP Franco’s JSI Module Tutorial</a>, <a href="https://github.com/mrousavy/react-native-mmkv">react-native-mmkv</a>, and <a href="https://github.com/margelo/react-native-quick-sqlite">react-native-quick-sqlite</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=908afd03c0f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can React Native Close the Performance Gap? A Dive into C++ Turbo Native Modules]]></title>
            <link>https://codeherence.medium.com/can-react-native-close-the-performance-gap-a-dive-into-c-turbo-native-modules-edd548c811f6?source=rss-a30cfac5ee5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/edd548c811f6</guid>
            <category><![CDATA[cross-platform]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[application-development]]></category>
            <category><![CDATA[expo]]></category>
            <dc:creator><![CDATA[codeherence]]></dc:creator>
            <pubDate>Thu, 13 Apr 2023 21:01:29 GMT</pubDate>
            <atom:updated>2023-04-13T21:01:29.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kBNWBDsP4lNZCymtrr61eA.png" /></figure><p>React Native has become a powerful and valuable tool for individuals and companies to develop cross-platform applications. However, one common pitfall of the technology is its performance when compared to native applications. This is especially true when it comes to compute-heavy tasks that need to be run on the JavaScript thread, such as compression, file IO, and streaming.</p><p>The React Native team at Meta recognized the technology’s performance drawbacks and developed a plan to restructure the framework’s architecture entirely — giving birth to <a href="https://reactnative.dev/docs/next/the-new-architecture/pillars-turbomodules">Turbo Modules</a> and <a href="https://reactnative.dev/architecture/fabric-renderer">Fabric</a>.</p><p>In this blog, we are going to dive into C++ Turbo Native Modules and compare the performance against JavaScript. Namely, we will write a simple React Native application that generates the n-th number in the Fibonacci sequence using the naive recursive implementation to simulate a compute-heavy task. For more information on how this algorithm works, see <a href="https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/">here</a>.</p><h3>Results</h3><p>Before running through the setup and implementation, I want to post the results first. Keep in mind that these results are from running the application in development mode, directly from my laptop.</p><p>After implementing the Fibonacci algorithm in C++ and JavaScript and running the algorithm on our application, we got the following results from the iOS simulator:</p><pre>n=20  cpp=0ms    js=3ms<br>n=22  cpp=0ms    js=4ms<br>n=25  cpp=1ms    js=19ms<br>n=28  cpp=3ms    js=75ms<br>n=30  cpp=6ms    js=198ms<br>n=36  cpp=106ms  js=3742ms<br>n=38  cpp=281ms  js=9353ms</pre><p>and on a physical Google 7 Pixel:</p><pre>n=20  cpp=0ms    js=2ms<br>n=22  cpp=0ms    js=7ms<br>n=25  cpp=3ms    js=21ms<br>n=28  cpp=3ms    js=84ms<br>n=30  cpp=7ms    js=154ms<br>n=36  cpp=124ms  js=2761ms<br>n=38  cpp=329ms  js=7878ms</pre><p>where <strong>n</strong> is the n-th number in the Fibonacci sequence, <strong>cpp </strong>is the duration it took our Turbo Module to compute it, and <strong>js</strong> is the duration it took our regular JavaScript implementation to compute it. Keep in mind that the two implementations are equivalent.</p><p>From the data above, we can see that we have improved the performance by at least an order of magnitude (sometimes up to 40x) by simply letting C++ do the work for us.</p><h3>Skip the Setup and Implementation</h3><p>If you would like to just clone the repository and run the tests on your device/simulators, here is how you can do it:</p><p>Clone the repository at <a href="https://github.com/e-younan/CxxTurboModulesGuide">https://github.com/e-younan/CxxTurboModulesGuide</a>.</p><p>Then install the project dependencies by running the following:</p><pre>cd CxxTurboModulesGuide<br>yarn install</pre><p>Then install the pod dependencies:</p><pre>cd ios &amp;&amp; RCT_NEW_ARCH_ENABLED=1 bundle exec pod install &amp;&amp; cd ..</pre><p>Lastly, simply run the application by running yarn ios or yarn android.</p><h3>Setup</h3><p>For the setup, we followed the <a href="https://reactnative.dev/docs/the-new-architecture/cxx-cxxturbomodules">C++ Turbo Native Modules guide</a> on the React Native website. The setup below is copied from there to help you get set up. We begin by creating the project:</p><pre>npx react-native init CxxTurboModulesGuide<br>cd CxxTurboModulesGuide<br>yarn install</pre><p>On Android, we enable the New Architecture by modifying the android/gradle.properties file:</p><pre>newArchEnabled=true</pre><p>On iOS enable the New Architecture when running pod install in the ios folder:</p><pre>RCT_NEW_ARCH_ENABLED=1 bundle exec pod install</pre><p>Now that we have the bare application set up, we can proceed with writing our Turbo Module that computes the n-th number in the Fibonacci sequence.</p><h3>Turbo Module</h3><p>In the root directory, we create a folder tm that will contain your C++ Turbo Modules for your application.</p><h3>1. JavaScript Specification</h3><p>Inside the tm folder, create a file NativeSampleModule.ts which will hold the spec of our Turbo Modules. Inside the file, paste the following:</p><pre>import type {TurboModule} from &#39;react-native/Libraries/TurboModule/RCTExport&#39;;<br>import {TurboModuleRegistry} from &#39;react-native&#39;;<br><br>export interface Spec extends TurboModule {<br>  readonly doFibExpensive: (n: number) =&gt; number;<br>}<br><br>export default TurboModuleRegistry.getEnforcing&lt;Spec&gt;(&#39;NativeSampleModule&#39;);</pre><h3>2. Codegen Configuration</h3><p>We need to add some configuration for <a href="https://reactnative.dev/docs/the-new-architecture/pillars-codegen">Codegen</a>.</p><h4>Application</h4><p>Update your app’s package.json file with the following entries:</p><pre>{<br>  // ...<br>  &quot;description&quot;: &quot;React Native with Cxx Turbo Native Modules&quot;,<br>  &quot;author&quot;: &quot;&lt;Evan Younan&gt; &lt;me@eyounan.com&gt; (https://github.com/e-younan)&quot;,<br>  &quot;license&quot;: &quot;MIT&quot;,<br>  &quot;homepage&quot;: &quot;https://github.com/e-younan/#readme&quot;,<br>  // ...<br>  &quot;codegenConfig&quot;: {<br>    &quot;name&quot;: &quot;AppSpecs&quot;,<br>    &quot;type&quot;: &quot;all&quot;,<br>    &quot;jsSrcsDir&quot;: &quot;tm&quot;,<br>    &quot;android&quot;: {<br>      &quot;javaPackageName&quot;: &quot;com.facebook.fbreact.specs&quot;<br>    }<br>  }<br>}</pre><p>It adds necessary properties which we will later re-use in the iOS podspec file and configures Codegen to search for specs inside the tm folder.</p><h4>iOS: Create the podspec file</h4><p>For iOS, you’ll need to create a AppTurboModules.podspec file in the tm folder - which will look like:</p><pre>require &quot;json&quot;<br><br>package = JSON.parse(File.read(File.join(__dir__, &quot;../package.json&quot;)))<br><br>Pod::Spec.new do |s|<br>  s.name            = &quot;AppTurboModules&quot;<br>  s.version         = package[&quot;version&quot;]<br>  s.summary         = package[&quot;description&quot;]<br>  s.description     = package[&quot;description&quot;]<br>  s.homepage        = package[&quot;homepage&quot;]<br>  s.license         = package[&quot;license&quot;]<br>  s.platforms       = { :ios =&gt; &quot;12.4&quot; }<br>  s.author          = package[&quot;author&quot;]<br>  s.source          = { :git =&gt; package[&quot;repository&quot;], :tag =&gt; &quot;#{s.version}&quot; }<br>  s.source_files    = &quot;**/*.{h,cpp}&quot;<br>  s.pod_target_xcconfig = {<br>    &quot;CLANG_CXX_LANGUAGE_STANDARD&quot; =&gt; &quot;c++17&quot;<br>  }<br>  install_modules_dependencies(s)<br>end</pre><p>and we modify our Podfile to recognize the module as a dependency, e.g., after the use_react_native!(...) section:</p><pre>  # ...<br><br>  use_react_native!(<br>    :path =&gt; config[:reactNativePath],<br>    # Hermes is now enabled by default. Disable by setting this flag to false.<br>    # Upcoming versions of React Native may rely on get_default_flags(), but<br>    # we make it explicit here to aid in the React Native upgrade process.<br>    :hermes_enabled =&gt; flags[:hermes_enabled],<br>    :fabric_enabled =&gt; flags[:fabric_enabled],<br>    # Enables Flipper.<br>    #<br>    # Note that if you have use_frameworks! enabled, Flipper will not work and<br>    # you should disable the next line.<br>    :flipper_configuration =&gt; flipper_config,<br>    # An absolute path to your application root.<br>    :app_path =&gt; &quot;#{Pod::Config.instance.installation_root}/..&quot;<br>  )<br><br>  target &#39;CxxTurboModulesGuideTests&#39; do<br>    inherit! :complete<br>    # Pods for testing<br>  end<br><br>  # To register our Turbo Module<br>  if ENV[&#39;RCT_NEW_ARCH_ENABLED&#39;] == &#39;1&#39;<br>    pod &#39;AppTurboModules&#39;, :path =&gt; &quot;./../tm&quot;<br>  end<br><br>  # ...</pre><h4>Android: build.gradle, CMakeLists.txt, Onload.cpp</h4><p>For Android, you’ll need to create a CMakeLists.txt file in the tm folder - which will look like:</p><pre>cmake_minimum_required(VERSION 3.13)<br>set(CMAKE_VERBOSE_MAKEFILE on)<br><br>add_compile_options(<br>        -fexceptions<br>        -frtti<br>        -std=c++17)<br><br>file(GLOB tm_SRC CONFIGURE_DEPENDS *.cpp)<br>add_library(tm STATIC ${tm_SRC})<br><br>target_include_directories(tm PUBLIC .)<br>target_include_directories(react_codegen_AppSpecs PUBLIC .)<br><br>target_link_libraries(tm<br>        jsi<br>        react_nativemodule_core<br>        react_codegen_AppSpecs)</pre><p>It defines the tm folder as a source for native code and sets up necessary dependencies.</p><p>You need to add it as a dependency to your application in android/app/build.gradle, e.g., at the very end of that file:</p><pre>android {<br>   // ...<br><br>   // Add this block<br>   externalNativeBuild {<br>       cmake {<br>           path &quot;src/main/jni/CMakeLists.txt&quot;<br>       }<br>   }<br><br>   // ...<br>}</pre><h3>3. Module Registration</h3><h4>iOS</h4><p>To register a C++ Turbo Native Module in your app you will need to update ios/CxxTurboModulesGuide/AppDelegate.mm . Let’s replace the contents of AppDelegate.mm with the following:</p><pre>#import &quot;AppDelegate.h&quot;<br><br>#import &lt;React/RCTBundleURLProvider.h&gt;<br>#import &lt;React/CoreModulesPlugins.h&gt;<br>#import &lt;ReactCommon/RCTTurboModuleManager.h&gt;<br>#import &lt;NativeSampleModule.h&gt;<br><br>@interface AppDelegate () &lt;RCTTurboModuleManagerDelegate&gt; {}<br>@end<br><br>@implementation AppDelegate<br><br>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions<br>{<br>  self.moduleName = @&quot;CxxTurboModulesGuide&quot;;<br>  // You can add your custom initial props in the dictionary below.<br>  // They will be passed down to the ViewController used by React Native.<br>  self.initialProps = @{};<br><br>  return [super application:application didFinishLaunchingWithOptions:launchOptions];<br>}<br><br>- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge<br>{<br>#if DEBUG<br>  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@&quot;index&quot;];<br>#else<br>  return [[NSBundle mainBundle] URLForResource:@&quot;main&quot; withExtension:@&quot;jsbundle&quot;];<br>#endif<br>}<br><br>/// This method controls whether the `concurrentRoot`feature of React18 is turned on or off.<br>///<br>/// @see: https://reactjs.org/blog/2022/03/29/react-v18.html<br>/// @note: This requires to be rendering on Fabric (i.e. on the New Architecture).<br>/// @return: `true` if the `concurrentRoot` feature is enabled. Otherwise, it returns `false`.<br>- (BOOL)concurrentRootEnabled<br>{<br>  return true;<br>}<br><br>#pragma mark RCTTurboModuleManagerDelegate<br><br>- (std::shared_ptr&lt;facebook::react::TurboModule&gt;)getTurboModule:(const std::string &amp;)name<br>                                                      jsInvoker:(std::shared_ptr&lt;facebook::react::CallInvoker&gt;)jsInvoker<br>{<br>  if (name == &quot;NativeSampleModule&quot;) {<br>    return std::make_shared&lt;facebook::react::NativeSampleModule&gt;(jsInvoker);<br>  }<br>  return nullptr;<br>}<br><br>@end</pre><p>This will instantiante a NativeSampleModule associated with the name NativeSampleModule as defined in our JavaScript spec file earlier.</p><h4>Android</h4><p>Android apps aren’t setup for native code compilation by default. I have provided you a set of convenience commands to create the necessary folders/files. Run the following from the root folder:</p><pre>cd android/app/src/main<br>mkdir jni<br>cd ../../../..<br>cp node_modules/react-native/ReactAndroid/cmake-utils/default-app-setup/CMakeLists.txt android/app/src/main/jni/<br>cp node_modules/react-native/ReactAndroid/cmake-utils/default-app-setup/OnLoad.cpp android/app/src/main/jni/</pre><p><strong>Manual</strong>:</p><p>If the commands above did not work for you, feel free to do the following manually:</p><p>1.) Create the folder android/app/src/main/jni</p><p>2.) Copy CMakeLists.txt and Onload.cpp from <a href="https://github.com/facebook/react-native/tree/0.71-stable/ReactAndroid/cmake-utils/default-app-setup">node_modules/react-native/ReactAndroid/cmake-utils/default-app-setup</a> into the android/app/src/main/jni folder.</p><p>Now, we update OnLoad.cpp with the following (i.e., add the lines with the starting with a + and remove the +):</p><pre>// ...<br><br>#include &lt;react/renderer/componentregistry/ComponentDescriptorProviderRegistry.h&gt;<br>#include &lt;rncli.h&gt;<br>+ #include &lt;NativeSampleModule.h&gt;<br><br>// ...<br><br>std::shared_ptr&lt;TurboModule&gt; cxxModuleProvider(<br>    const std::string &amp;name,<br>    const std::shared_ptr&lt;CallInvoker&gt; &amp;jsInvoker) {<br>+ if (name == &quot;NativeSampleModule&quot;) {<br>+   return std::make_shared&lt;facebook::react::NativeSampleModule&gt;(jsInvoker);<br>+ }<br>  return nullptr;<br>}<br><br>// ...</pre><p>and update CMakeLists.txt in the <strong>jni</strong> folder with the following entries, e.g., at the very end of that file (remove the +’s):</p><pre>// ...<br><br># This file includes all the necessary to let you build your application with the New Architecture.<br>include(${REACT_ANDROID_DIR}/cmake-utils/ReactNative-application.cmake)<br><br>+ # App needs to add and link against tm (TurboModules) folder<br>+ add_subdirectory(${REACT_ANDROID_DIR}/../../../tm/ tm_build)<br>+ target_link_libraries(${CMAKE_PROJECT_NAME} tm)</pre><p>This will instantiate a NativeSampleModule associated with the name NativeSampleModule as defined in our JavaScript spec file earlier.</p><h3>4. C++ Native Code</h3><p>For the final step, we need to connect the JavaScript side to the native platforms. This involves two steps:</p><ul><li>Run <a href="https://reactnative.dev/docs/next/the-new-architecture/pillars-codegen">Codegen</a><strong> </strong>to see what it generates</li><li>Write your native code, implementing the generated interfaces.</li></ul><p>On iOS Codegen is run each time you execute in the ios folder:</p><pre>RCT_NEW_ARCH_ENABLED=1 bundle exec pod install</pre><p>On Android Codegen is run each time you execute:</p><pre>yarn android</pre><p>Keep in mind that you need to re-run Codegen if you have changed your JavaScript spec.</p><h3>Implementation</h3><p>Now create a NativeSampleModule.h file in the tm folder with the following content:</p><pre>#pragma once<br><br>#if __has_include(&lt;React-Codegen/AppSpecsJSI.h&gt;) // CocoaPod headers on Apple<br>#include &lt;React-Codegen/AppSpecsJSI.h&gt;<br>#elif __has_include(&quot;AppSpecsJSI.h&quot;) // CMake headers on Android<br>#include &quot;AppSpecsJSI.h&quot;<br>#endif<br>#include &lt;memory&gt;<br>#include &lt;string&gt;<br><br>namespace facebook::react<br>{<br><br>  class NativeSampleModule : public NativeSampleModuleCxxSpec&lt;NativeSampleModule&gt;<br>  {<br>  public:<br>    NativeSampleModule(std::shared_ptr&lt;CallInvoker&gt; jsInvoker);<br><br>    int doFibExpensive(jsi::Runtime &amp;rt, int n);<br>  };<br><br>} // namespace facebook::react</pre><p>And now, we add a NativeSampleModule.cpp file in the tm folder with an implementation of the recursive Fibonacci for it:</p><pre>#include &lt;fstream&gt;<br>#include &quot;NativeSampleModule.h&quot;<br><br>namespace facebook::react<br>{<br><br>  NativeSampleModule::NativeSampleModule(std::shared_ptr&lt;CallInvoker&gt; jsInvoker)<br>      : NativeSampleModuleCxxSpec(std::move(jsInvoker)) {}<br><br>  int NativeSampleModule::doFibExpensive(jsi::Runtime &amp;rt, int n)<br>  {<br>    if (n &lt; 2)<br>    {<br>      return n;<br>    }<br>    else<br>    {<br>      return doFibExpensive(rt, n - 1) + doFibExpensive(rt, n - 2);<br>    }<br>  }<br>} // namespace facebook::react</pre><p>And lastly, since we have added new C++ files, we run the following in the ios folder again:</p><pre>RCT_NEW_ARCH_ENABLED=1 bundle exec pod install</pre><h3>5. Adding the C++ Turbo Native Module to the App</h3><p>Keep in mind that the App.tsx files should exist in the root folder. Replace your App.tsx with the following:</p><pre>import React, {useState} from &#39;react&#39;;<br>import {<br>  SafeAreaView,<br>  Text,<br>  StyleSheet,<br>  View,<br>  ScrollView,<br>  Button,<br>} from &#39;react-native&#39;;<br>import NativeSampleModule from &#39;./tm/NativeSampleModule&#39;;<br><br>const TESTS = [20, 22, 25, 28, 30, 36, 38];<br><br>const doJsFib = (n: number): number =&gt; {<br>  if (n &lt; 2) {<br>    return n;<br>  }<br>  return doJsFib(n - 1) + doJsFib(n - 2);<br>};<br><br>const doFibTest = async (n: number) =&gt; {<br>  // Wait 100ms before starting the test to allow the app to settle and render new results<br>  await new Promise(res =&gt; setTimeout(() =&gt; res(null), 100));<br><br>  let before = Date.now();<br>  // C++<br>  NativeSampleModule.doFibExpensive(n);<br>  const duration = Date.now() - before;<br><br>  before = Date.now();<br>  // JS<br>  doJsFib(n);<br>  const duration2 = Date.now() - before;<br><br>  return [duration, duration2] as const;<br>};<br><br>interface FibonacciTestResult {<br>  n: number;<br>  cppDuration: number;<br>  jsDuration: number;<br>}<br><br>export default function App(): JSX.Element {<br>  const [running, setRunning] = useState(false);<br>  // Store the results of the tests<br>  const [results, setResults] = useState&lt;FibonacciTestResult[]&gt;([]);<br><br>  const onPressStart = async () =&gt; {<br>    if (running) {<br>      return;<br>    }<br><br>    setRunning(true);<br><br>    for await (const n of TESTS) {<br>      const [cppDuration, jsDuration] = await doFibTest(n);<br>      setResults(prev =&gt; [...prev, {n, cppDuration, jsDuration}]);<br>    }<br><br>    setRunning(false);<br>  };<br><br>  return (<br>    &lt;SafeAreaView style={styles.container}&gt;<br>      &lt;ScrollView style={styles.scrollStyle}&gt;<br>        &lt;Text style={styles.title}&gt;C++ vs JS Fibonacci Test&lt;/Text&gt;<br>        &lt;Button<br>          disabled={running}<br>          title={running ? &#39;Running - please wait...&#39; : &#39;Start test&#39;}<br>          onPress={onPressStart}<br>        /&gt;<br><br>        &lt;View style={styles.titleRow}&gt;<br>          &lt;Text style={styles.boldText}&gt;n&lt;/Text&gt;<br>          &lt;Text style={styles.boldText}&gt;C++&lt;/Text&gt;<br>          &lt;Text style={styles.boldText}&gt;JS&lt;/Text&gt;<br>        &lt;/View&gt;<br><br>        &lt;View style={styles.resultsContainer}&gt;<br>          {results.map((test, i) =&gt; (<br>            &lt;View style={styles.resultRow} key={`test-${i}`}&gt;<br>              &lt;Text style={styles.text}&gt;{test.n}&lt;/Text&gt;<br>              &lt;Text style={styles.text}&gt;{test.cppDuration}ms&lt;/Text&gt;<br>              &lt;Text style={styles.text}&gt;{test.jsDuration}ms&lt;/Text&gt;<br>            &lt;/View&gt;<br>          ))}<br>        &lt;/View&gt;<br>      &lt;/ScrollView&gt;<br>    &lt;/SafeAreaView&gt;<br>  );<br>}<br><br>const styles = StyleSheet.create({<br>  container: {<br>    flex: 1,<br>    backgroundColor: &#39;white&#39;,<br>  },<br>  scrollStyle: {<br>    flex: 1,<br>  },<br>  button: {<br>    backgroundColor: &#39;lightblue&#39;,<br>    padding: 10,<br>    justifyContent: &#39;center&#39;,<br>    alignItems: &#39;center&#39;,<br>  },<br>  resultsContainer: {<br>    marginTop: 20,<br>    gap: 8,<br>  },<br>  titleRow: {<br>    marginTop: 20,<br>    width: &#39;100%&#39;,<br>    alignItems: &#39;center&#39;,<br>    flexDirection: &#39;row&#39;,<br>  },<br>  resultRow: {<br>    width: &#39;100%&#39;,<br>    alignItems: &#39;center&#39;,<br>    flexDirection: &#39;row&#39;,<br>  },<br>  text: {<br>    flex: 1,<br>    textAlign: &#39;center&#39;,<br>  },<br>  boldText: {<br>    flex: 1,<br>    fontWeight: &#39;bold&#39;,<br>    textAlign: &#39;center&#39;,<br>  },<br>  title: {<br>    fontSize: 20,<br>    fontWeight: &#39;bold&#39;,<br>    marginVertical: 12,<br>    textAlign: &#39;center&#39;,<br>  },<br>});</pre><p>What you should notice is the function doFibTest will run the algorithm using our C++ Turbo Module and a JavaScript equivalent, and store the results of the computations (i.e., how long each took in milliseconds) to display on the UI. If you would like to review the performance differences between the C++ and JavaScript implementation, they are posted above in the <strong>Results </strong>section.</p><h3>Conclusion</h3><p>It is clear that with the introduction of Turbo Modules, applications that require heavy computation can offload the work to C++ and increase performance drastically. Some libraries have already migrated and are taking advantage of the new benefits C++ Turbo Modules have introduced into the ecosystem — check out <a href="https://github.com/mrousavy/react-native-mmkv">react-native-mmkv</a>, for example.</p><p>Since the re-architecture of React Native which introduced Turbo Modules and Fabric, the performance gap between applications developed using it and native applications has started closing.</p><h4><strong>Get in touch</strong></h4><p>If you or your organization are seeking to develop highly interactive and high-performance cross-platform applications, we invite you to <a href="https://codeherence.com/">connect with us</a> and explore how our expertise can benefit your project.</p><h3>Follow me</h3><p>If you would like to see more content like this, make requests on the type of content you want to see, etc., feel free to:</p><ol><li>Follow <a href="https://twitter.com/e_younan">my Twitter</a></li><li>Join my <a href="https://discord.gg/aseNHjaUQB">Discord</a></li><li>Follow me on <a href="https://www.linkedin.com/in/evan-younan-027160181/">LinkedIn</a></li></ol><p>In the upcoming weeks, I will be working on creating libraries that take advantage of C++ Turbo Modules to improve the performance of specific use cases that are common in React Native applications. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edd548c811f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building the Animated Twitter Profile Header with React Native Header]]></title>
            <link>https://codeherence.medium.com/building-the-animated-twitter-profile-header-with-react-native-header-a22a2b26c109?source=rss-a30cfac5ee5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a22a2b26c109</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[reanimated]]></category>
            <dc:creator><![CDATA[codeherence]]></dc:creator>
            <pubDate>Thu, 30 Mar 2023 09:46:46 GMT</pubDate>
            <atom:updated>2023-04-28T01:01:51.392Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="The Twitter profile header in a non-collapsed and collapsed state." src="https://cdn-images-1.medium.com/max/1024/1*BYbDQMDKENZf2QgtVFTotQ.png" /></figure><p>Following the release of <a href="https://codeherence.com/">our</a> new library, <a href="https://www.npmjs.com/package/@codeherence/react-native-header">react-native-header</a>, which enables developers to create cross-platform animated headers in React Native, we set out to design a custom header that would:</p><ul><li>Demonstrate the ease of using the library to build visually appealing headers</li><li>Enhance the library’s implementation</li></ul><p>The Twitter profile header on the mobile application stands out for its deviation from the “native” feel, showcasing an impressive and aesthetically pleasing design. As a result, I selected it for this project. You can view the Twitter profile header in action via this <a href="https://giphy.com/gifs/rQu6W8i3IEOfiWYphq">GIPHY link</a>, which provides a gif showcasing its features.</p><h3>Setting up</h3><p>The implementation of the header exists <a href="https://github.com/codeherence/react-native-header/tree/main/example">under the <strong>example </strong>folder of the <strong>react-native-header </strong>library</a>.</p><p>Let’s begin by downloading the repository onto your machine:</p><ol><li>Click <a href="https://github.com/codeherence/react-native-header/fork">here</a> and press on the button “Create fork” to fork the repository.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*ABGnHuco0C9L5mTFinnXoA.png" /></figure><p>2. Once the repository is forked, navigate to the fork and clone it on your machine by opening a terminal and running</p><pre>git clone https://github.com/&lt;YOUR_USERNAME&gt;/react-native-header.git</pre><p>and replacing &lt;YOUR_USERNAME&gt; with your GitHub username. If you’re having difficulty forking and cloning the repository, visit the <a href="https://docs.github.com/en/get-started/quickstart/fork-a-r">GitHub documentation on how to fork a repo</a>.</p><h3>Running the application</h3><p>Once you have cloned the repository onto your machine, run the following to install the dependencies in the root folder:</p><pre>cd react-native-header &amp;&amp; yarn</pre><p>Then, install the dependencies for the example Expo application:</p><pre>cd example &amp;&amp; yarn</pre><p>If you’re testing the application on an iOS device/simulator, make sure to install the Pod dependencies after:</p><pre>npx pod-install</pre><p>Then, we can run the application by opening <strong>2</strong> terminals and executing:</p><pre>yarn start</pre><p>in one of them, and</p><pre>yarn run ios</pre><p>in the other if you are running the application on an <strong>iOS</strong> device/simulator, or</p><pre>yarn run android</pre><p>if you are running it on an <strong>Android</strong> device/emulator.</p><h3>Let’s Analyze</h3><p>The main file that implements the Twitter profile header can be found at: example/src/screens/usage/TwitterProfile.tsx</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y8L9EZH3XSOIZYSMX9UGUQ.png" /><figcaption>What the example looks like on an iPhone 14 Pro Max simulator</figcaption></figure><p>When we tap the button labeled “Twitter Profile” in the application, we are presented with the mock Twitter profile header.</p><p>This screen consists of several components:</p><ul><li>TwitterProfile — The primary component responsible for rendering all elements on the screen.</li><li>LargeHeaderComponent — This component encompasses the large header, starting from the user’s name, extending to the row displaying the user’s followers, and showcasing up to three preview images.</li><li>HeaderComponent — Positioned at the top of the screen, this component comprises the navigation buttons and the navigation header, which becomes visible as the user scrolls upward. Additionally, the component features a banner image for the Twitter profile that dynamically blurs upon scrolling.</li><li>SomeComponent and MemoizedComponent — these components are only used to fill up the list so we can test the scrolling animations on our headers. Ignore these components.</li></ul><h3>The Header</h3><p>Within the header, we implement a majority of the animations showcased in the <a href="https://giphy.com/gifs/rQu6W8i3IEOfiWYphq">GIPHY link</a>. These animations are primarily influenced by the scroll position of the list, resulting in a smooth and interactive user experience.</p><pre>const HeaderComponent: React.FC&lt;ScrollHeaderProps&gt; = ({ showNavBar, scrollY }) =&gt; {<br>  // ...<br>};</pre><p>We started by defining a functional React component named HeaderComponent, which accepts the ScrollHeaderProps type as its props. The props include showNavBar, which determines whether the navigation bar children should be shown or not, and scrollY, a reanimated shared value that represents the scroll position on the Y-axis. The showNavBar and scrollY values are provided by the library itself to the HeaderComponent and LargeHeaderComponent props of the SectionListWithHeaders.</p><p>Now, we have a few things to animate:</p><ol><li>The blurring of the banner when the scrollY value is not 0 (i.e., the user has scrolled up or down)</li><li>The scaling of the banner on iOS when the list is pulled down</li><li>The upwards translation of the banner when the user scrolls up, until it matches the height of the smaller header</li><li>The profile image’s scaling and translation</li><li>The change of the zIndex of the profile image &amp; follow button so that it goes behind the header bar while the user scrolls up</li></ol><p>We begin with the blurring of the banner <strong>(1):</strong></p><pre>const blurOpacity = useDerivedValue(() =&gt; {<br>  return interpolate(<br>    Math.abs(scrollY.value), <br>    [0, 40], <br>    [0, 1], <br>    Extrapolate.CLAMP<br>  );<br>});</pre><p>Here, we create a derived value using useDerivedValue to calculate the blur opacity of the banner based on the scroll position. The interpolate function maps the scrollY value to an opacity value between 0 and 1, enabling the blur effect to appear as the user scrolls up or down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*vDZV4Pma73tfKrDQwfq__A.gif" /><figcaption>The BlurView animating in and out based on the scroll position</figcaption></figure><p>The scaling of the banner <strong>(2) </strong>was achieved through a convenience component, <a href="https://react-native-header.codeherence.com/docs/components/scaling-view">ScalingView</a>, that is exported from react-native-header:</p><pre>&lt;ScalingView<br>  scrollY={scrollY}<br>  translationDirection=&quot;none&quot;<br>  // These two values were arbitrarily chosen.<br>  // Will need to adjust scaling view to allow for scale translations to separate<br>  // x, y and z.<br>  endScale={6}<br>  endRange={height * 0.43}<br>&gt;<br>  {/* ... Banner Image &amp; BlurView ... */}<br>&lt;/ScalingView&gt;</pre><p>The upwards translation of the profile banner <strong>(3)</strong> was simply done by:</p><pre>const bannerTranslation = useDerivedValue(() =&gt; {<br>  return interpolate(<br>    scrollY.value,<br>    [0, BANNER_BOTTOM_HEIGHT_ADDITION],<br>    [0, -BANNER_BOTTOM_HEIGHT_ADDITION],<br>    Extrapolate.CLAMP<br>  );<br>});</pre><p>and the profile image’s scaling and translation <strong>(4):</strong></p><pre>const profileImageScale = useDerivedValue(() =&gt; {<br>  return interpolate(<br>    scrollY.value,<br>    [0, AVATAR_SIZE_VALUE],<br>    [AVATAR_START_SCALE, AVATAR_END_SCALE],<br>    Extrapolate.CLAMP<br>  );<br>});<br><br>const profileImageTranslationY = useDerivedValue(() =&gt; {<br>  return interpolate(<br>    profileImageScale.value,<br>    [AVATAR_START_SCALE, AVATAR_END_SCALE],<br>    [0, AVATAR_SIZE_VALUE / 2],<br>    Extrapolate.CLAMP<br>  );<br>});</pre><p>Here, profileImageScale calculates the scaling factor for the profile image based on the scroll position (scrollY). When the user scrolls up, the profile image will gradually scale down, and when the user scrolls down, the profile image will scale up.</p><p>profileImageTranslationY calculates the translation value for the profile image on the Y-axis based on the <strong>profileImageScale</strong>. As the profile image scales down, we want to ensure that it appears to stay in the same position relative to the bottom. To achieve this, we use the interpolate function to map the profileImageScale value to a range of translation values (0 to <strong>AVATAR_SIZE_VALUE</strong> / 2).</p><p>As the profile image scales down (scrolling up), it will also translate upwards by half of the <strong>AVATAR_SIZE_VALUE</strong>, which compensates for the scaling effect and gives the impression that the image is becoming smaller without moving from its position relative to the bottom.</p><p>Finally, we implement the zIndex modifier on the profile image &amp; follow button container <strong>(5):</strong></p><pre>const rootProfileRowZIndexStyle = useAnimatedStyle(() =&gt; {<br>  return {<br>    zIndex: profileImageScale.value &lt;= AVATAR_END_SCALE ? -1 : 1,<br>  };<br>});</pre><p>This code ensures that the profile image hides behind the header once it has been scaled down.</p><p>In this tutorial, we are not going to go through the JSX. Now that you have an understanding of the animation values and what they’re being used for, feel free to dig into the header code!</p><h3>The Large Header</h3><p>The large header implementation is not exactly very interesting, since all it does is define the views between the name of the user and their follower statistics via simple React Native components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*2upOlFwSVIJwWgZkdqup0g.png" /></figure><h3>Conclusion</h3><p>In this blog post, we explored the implementation of a Twitter profile header that showcases a range of dynamic and interactive features such as a blurred banner view on scroll, a scaling banner on pull-down, and a profile image that scales down and hides behind the header while scrolling up. By leveraging the power of the react-native-header library, we were able to eliminate the need for a significant amount of boilerplate code to achieve the following:</p><ol><li>Expose the scroll position: Instead of writing our own custom code to track and update the scroll position, react-native-header provides us with an efficient and straightforward way to access the current scroll position (scrollY) and use it for calculations in our animations.</li><li>Expose whether or not to show the header navigation bar’s children: The library offers an easy method to determine when to show or hide specific elements in the navigation bar, such as icons and text, depending on the scroll position.</li><li>Integrate everything into a <a href="https://react-native-header.codeherence.com/docs/components/section-list-with-headers">SectionListWithHeaders</a>: With react-native-header, we can seamlessly combine all the aforementioned features and animations into a single <a href="https://react-native-header.codeherence.com/docs/components/section-list-with-headers">SectionListWithHeaders</a> component that offers a smooth and interactive user experience.</li></ol><p>By using react-native-header, react-native-reanimated and the techniques discussed in this blog post, developers can create engaging, performant and visually appealing user interfaces for their mobile applications. The Twitter profile header serves as a great example of how we can use the library to simplify the development process and deliver high-quality, interactive, and visually captivating experiences to our users.</p><h4>Get in touch</h4><p>If you or your organization are seeking to develop highly interactive and high-performance cross-platform applications, we invite you to <a href="https://codeherence.com/">connect with us</a> and explore how our expertise can benefit your project.</p><h4>Follow me</h4><p>If you would like to see more content like this, make requests on the type of content you want to see, etc., feel free to:</p><ol><li>Follow <a href="https://twitter.com/e_younan">my Twitter</a></li><li>Join my <a href="https://discord.gg/aseNHjaUQB">Discord</a></li><li>Follow me on <a href="https://www.linkedin.com/in/evan-younan-027160181/">LinkedIn</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a22a2b26c109" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>