Code reuse intends to save time, resources, and reduce redundancy by taking benefit of assets that have already been designed or developed in some form within the software product development process.
You can reuse a lot of code between React and React Native but don’t overreach on what you’re sharing. Doing so may leave your code harder to maintain where you’re trying to simplify differences between mobile and web.
You’ll certainly have to write your components separately for a mobile app and web app. But you can always reuse the business logic, API Communication layer.
- Business logic
- Communication with API
- Stores, Reducers, Actions and Services
- Helpers, Constants, Storage Services
- HOCs (Higher-Order Components)
Mobile / Web-specific:
- Presentational components
- Navigation / routing
Setting up a shared project
- Make sure you are at the project root folder
$ mkdir -p packages/components/src packages/mobile packages/web
- Create react native project using
- Create react app using
package.jsonat the root directory to enable Yarn Workspaces
Create a shared folder
Now create a common or shared folder where the common code of react and react native will exist.
$ mkdir -p packages/common
package.jsonfile in common folder
- Name the package and add main(entry file)
Enable yarn workspace package.json
Configure React Web application
react-app-rewired in dev dependencies in your
Change your scripts from react-scripts to react-app-rewired
"start": "react-app-rewired start"
"build": "react-app-rewired build"
"test": "react-app-rewired test --env=jsdom"
"eject": "react-app-rewired eject"
config-overrides.js inside web
Now run yarn to install the dependencies.
Configure React Native Mobile application
Configuring React Native on the mono repo is a little bit tricky part. We need to understand two things before making workspaces work in our react native app.
- No Hoist
These packages will only be available for mobile and they will not be hoisted globally in our app. You can do this by simply adding
nohoist under the workspaces in
symlink is a term for any file that contains a reference to another file or packages. To achieve symlinking we will use wml.
- Install wml globally
npm install -g wml
- Add your project directory in wml using a command. In the root directory of your project, run the following:
wml add packages/commonpackages/mobile//node_modules/@monorepo/common
- Run wml
Add common folder link in mobile node_modules
Now run wml start and you have achieved symlinking.
Develop and Import your functions from the shared folder to web and mobile components. Run your application and both applications should run and reuse the same code.