How to re-use code in multiple react-native projects?
I have so many react-native projects and most of them required the same logic in many parts of the app. like the same hooks, same util functions, and identical components.
I am copying and pasting all the code to other projects. Ya I know that’s a bad approach. If I change some code in some hooks then I have to update all the projects with it. and that’s very bug prone
I don’t know much yet about how to solve this problem, but I did some search and I found that
- I can try to create a JS library and a git submodule, and use them in all projects.
- build JS library and publish it to npm.
I am not sure how react-native would work for both of these approaches.
Will I need to create react native module? or do something else? If you have some resources to read please attach some as I couldn’t find much on google.
Solution – 1
Before segmenting your code, make sure you distinguish your business logic and other Logic reduce their dependencies.
Here Approach can vary depending on your use case,
Firstly about the tooling you need to use,
Git submodules has a steep learning curve, would be recommended using one git submodule, for all shared code, instead of several submodules as their were many issue with git submodules like dependency relationships between the modules, pull in the parent doesn’t pull child code etc and many more
If you feel all your code can fit into a submodule without issues with dependencies, you can try this approach
you can find more details here npm vs git submodules
Coming to other approaches, out goal was to create the reusable components or code. your code as components and others
For sharable Components you can use different approach’s like:-
Bit – for components
bit – it works with react native too
For Hooks and utils you can create npm packages directly or you can also use react-native-builder-bob but that would be a overhead as it will include react-native ,
Choose wisely how do many package/s needed because your components or utils can be like a collection or individual working set, depending on the functionally as all code can fit in single package or many.