Profile ImageDaniel Bischoff
tagged in React • Dec 31, 20172 min read

Share code between react and react-native apps

You created your mobile application with react-native and mobx, but now you want to offer your customers a desktop/web app too (or vise versa). As smart developers, we want to reuse as much existing code as possible to speed up our development and to prevent duplicated code. This article is about what parts of your application you can reuse and what parts you can not/should not reuse.

Parts to reuse

When you have read my previous articles and followed the guidelines, your application consists of the following parts:

  • Stores
  • Services
  • Components (smart/dumb)

Stores

The stores hold our application’s state and contain the business logic. Here is the biggest potential for code reuse as the business logic and the application’s state should not differ that much from our react-native application.

What can be different for example, is the application’s route store. In your web app, you also want the route store to update the browser’s history (url) while navigating your app or render a specific component when a new url is manually entered. In a react-native application, you don’t have any url.

Services

The services are the interfaces to our backend or the underlying operating system (File system etc.). As services should contain no logic and are only used to wrap calls to external resources (OS functions), there is no need in reusing them anyway.

Components (smart/dumb)

Although components make up most of our applications code, reusing them is very hard and can even slow us down during development. The ui differences between web and native applications are often very huge, so that programming reusable components can slow us down and the reusable code/logic we get might not be worth it.

Project structure

Refering to my previous article about your application’s project structure, a project that can easily be reused between react and react-native apps, has all reusable stores under one folder, so we can easily extract/import that folder to our react web app. So the following two project structures make perfect sense:

  • The project structure by type
  • A mixture of type and functionality

To sum up, what you can easily reuse are your application’s stores. They represent your applications state and business logic, and that’s where your two projects overlap. Even if it is tempting to reuse your ui components, in my opinion, the code you can reuse vs. the effort to make it reusable, is not worth the hassle or might even slow you down during development.

Liked the article? Share it!

Tweet