<?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 Andrei Lomtev on Medium]]></title>
        <description><![CDATA[Stories by Andrei Lomtev on Medium]]></description>
        <link>https://medium.com/@andrei.lomtev?source=rss-d8d957c79964------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*X4f_VD8DksNDk4pp</url>
            <title>Stories by Andrei Lomtev on Medium</title>
            <link>https://medium.com/@andrei.lomtev?source=rss-d8d957c79964------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 05:04:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andrei.lomtev/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[Architecture pattern for React Native applications]]></title>
            <link>https://blog.stackademic.com/architecture-pattern-for-react-native-applications-906fff65ebf8?source=rss-d8d957c79964------2</link>
            <guid isPermaLink="false">https://medium.com/p/906fff65ebf8</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[folder-structure]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Andrei Lomtev]]></dc:creator>
            <pubDate>Sun, 06 Oct 2024 01:29:26 GMT</pubDate>
            <atom:updated>2024-10-14T06:33:27.917Z</atom:updated>
            <content:encoded><![CDATA[<p>React Native is a popular cross platform framework for building mobile applications. Inheriting React declarative programming style, it allows manipulate native views and platforms APIs with JavaScript (or TypeScript).</p><p>The question of your app architecture arises when you need to access considerable number of native APIs, add new features, or reuse existing components or code. Here are some articles that trying to answer on question of React Native app architecture and folder structure:</p><p>-<a href="https://github.com/alan2207/bulletproof-react">bulletproof-react</a></p><p><a href="https://github.com/infinitered/ignite">-Infinite Red’s battle-tested React Native project boilerplate</a></p><p><a href="https://www.waldo.com/blog/react-native-project-structure">-React Native Project Structure: A Best Practices Guide</a></p><p><a href="https://www.etatvasoft.com/blog/react-architecture-patterns/">-A Definitive Guide to React Architecture Patterns</a></p><p>In this article I would like to look at the project architecture that will be independent from the external libraries and would allow to build scalable and testable applications. The architecture inspired by feature-based pattern and clean architecture principles.</p><h3>Understanding app logic</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*O7LQZBh2D4wYT44SlbzrTg.gif" /><figcaption><a href="https://i.giphy.com/media/v1.Y2lkPTc5MGI3NjExajRjaTFwNThoeGNuN3dwaTJ6b2t1dTBqdGgzdzFkdGFsZ2lhemVnaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/GPQL5xsaunjmGcVqLn/giphy.gif">giphy.gif (480×400)</a></figcaption></figure><p>React native application can be divided into three layers:</p><ul><li>Display layer</li><li>Presentation logic</li><li>Business logic</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KnM8SKAtXKi6i1NraedouQ.png" /></figure><p><strong>Display layer</strong> is your components (views, texts, etc.). Components should be as simple as possible and should not have any state. They receive props (state values and callbacks) from parents, hooks, or context and their primary focus is to display content to the user. Primarily, this layer is JSX code with styling. Styles can also be separated from the components if you prefer CSS-like approach.</p><p><strong>Presentation logic</strong> is responsible for manipulating the <em>Display layer</em>. It consists of state hooks, effects, and callback functions. It is your custom hooks that will provide data to your components and will control how they should change in a result of user interactions.</p><p><strong>Business logic</strong> is what makes the core of your application. It manages the data, that you receive from the remote server, native mobile APIs or computed on the device and passes it to <em>Presentation logic</em>. It can be almost invisible if you just fetching JSON from the server and putting it to state or consist of many layers that we will discuss below.</p><p>Layer separation is important. You want to have <em>Presentation logic</em> separate to have different components for various platforms or screen sizes. You also want <em>Business</em> and <em>Presentation logic</em> separate from each other, because they can change frequently and independently.</p><p>Let dive into organizing each layer for a React Native application.</p><h3>Managing Display layer and Presentation logic</h3><p>Firstly, we can create folder <em>src</em> in the root react native folder, where all our JS/TS code will be stored.</p><h4>Feature based design</h4><p>One of the approaches to organize display layer with presentation logic is a feature-based approach. It breaks down your code into independent features that do not have cross dependencies. Each feature has its own components, hooks, util functions and <em>index.tsx</em> file where you export it. To avoid writing tons of same looking buttons, you can have global components that can be imported to all the features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*c30Lq4qkyjHCo-ZyJatDBQ.png" /><figcaption>Break your app down into features that are independent from one another</figcaption></figure><p>In the example above we have two features: <em>auth</em> and <em>home</em>. Usually, a feature can take a whole screen or be a small part of it. Features can be spread across multiple screens; in that case you would have multiple exports in <em>index.tsx</em> file.</p><h4>Navigation and screens</h4><p><em>Navigation</em> folder contains screens and navigation logic for your application. In our example we use React Navigation library, therefore we have our screen components and root navigator component. Screens should only import features and can have basic styling to arrange them together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*p3fobRP-0FUO04FiwDFNbQ.png" /><figcaption>Screens import features and managing data passed between features</figcaption></figure><p>Hooks inside navigation folder refer to hooks that return global level state or run global level effects. For example, determining if user is logged in, obtaining the access token on app launch, initializing database. All these operations should be executed in the hook that should be placed inside <em>RootNavigator.tsx</em> or <em>App.tsx</em>. Screen hooks can also be stored there. Screen hooks manage data inside each screen in cases when one feature depend on data from another feature.</p><h4>State management</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*8HACOqcRqIwMaqPzjVRU-w.png" /><figcaption>Global app state saved in “store” folder</figcaption></figure><p><em>Store</em> folder is where you keep the global app state. In our example we use Redux, but you can use any other state management library instead. It is up to you to decide what state should be considered global. Start by counting how many features will use the data from the state. If it is more than one, than you most likely should store it globally.</p><h4>Assets, helpers, constants</h4><p>Root level helpers folder contains functions that could be used in various parts of the applications, for example formatting time, field validation, error handling alerts. Constants may contain app specific constant values, and asset folder contains fonts, images etc.</p><p>This architecture gives clear separation between features and at the same time allows for code reusability with common components and util functions. However, we have only covered our presentation logic and views, leaving business logic aside.</p><h3>Business logic</h3><h4>What is business logic?</h4><p>To see a difference between <em>Business</em> and <em>Presentation</em> logic, we can look at the example below.</p><pre>const useMyData = () =&gt; {<br>    const [data, setData] = useState(null)<br><br>    useEffect(() =&gt; {<br>        const loadData = async () =&gt; {<br>            const { lat, lon } = await getCoordinatesFromTheDevice()<br>            const values = await remoteApiCall(&#39;https://myBackend.data&#39;, lat, lon)<br>            const convertedData = doSomethingWithJSON(values)<br>            setData(convertedData)<br>        }<br>        loadData()<br>    }, [])<br><br>    return data<br>}</pre><p>In the hook we are requesting user GPS coordinates and then sending them to our endpoint to obtain related data. After fetching the values, we work on them a little and setting to the state.</p><p>While setting values to the state on the component mount is <em>Presentation logic</em>, obtaining GPS coordinates and passing them to the backend is <em>Business logic</em>. Ideally, you should have a single function that would manage permissions, get users GPS and send HTTP request outside the hook and either show user the data or display an error message.</p><p>In a small app we would be OK with a single file called something like APIs or requests, where we would store our endpoints and other related functions. However, it will quickly become unmanageable, when you want to use various APIs or native packages for accessing filesystem, Bluetooth, geolocation and want to reuse them in the various parts of your application. Therefore, <em>Business logic</em> requires its own organization.</p><h4>Breaking down Business logic into the layers</h4><p>We can set up business logic in a server-like approach, adapting clean architecture principles to separate code into small classes that belongs to different layers. Our most outer layer should contain a controller function, which is called inside the hook and would return final data that is required inside the component. Another layer will be responsible for accessing native APIs via 3rd party packages providing coherent and clean interface adopted for our application. And finally, another layer will be responsible for executing business logic and passing data between other two layers. To accommodate business logic, we will create “<em>src/app”</em> folder with the following subfolders:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*vcVDtHbvs9L89kfzf7A0pQ.png" /><figcaption>Business logic is divided into four layers — Entities, Repositories, Services and Controllers</figcaption></figure><p>Let’s take a closer look at these layers and observe how data flows between them.</p><h4>Entities</h4><p><strong>Entities</strong> is the core of your business logic. These are the classes that will least likely change in the future. They describe data models that your application operates with. Entities could have methods, which should only operate with their own properties. They should not import any other classes except for constants or other entities. Here is the example of an entity in a simple To Do list application:</p><pre>export class TodoItem {<br>    id: number | null<br>    value: string<br>    completed: boolean<br>    completionTime?: number<br><br>    constructor(<br>        id: number | null<br>        value: string,<br>        completed: boolean,<br>        completionTime?: number | null) {<br>        this.id = id<br>        this.value = value<br>        this.completed = completed<br>        this.completionTime = completed &amp;&amp; completionTime !== null ? completionTime : undefined<br>    }<br><br>    makeCompleted(completionTime: number) {<br>        this.completed = true<br>        this.completionTime = completionTime<br>    }<br><br>    makeNotCompleted() {<br>        this.completed = false<br>        this.completionTime = undefined<br>    }<br>}</pre><h4>Repositories</h4><p>Repositories are wrappers around native APIs and packages. Repositories add abstraction layer for how data is obtained from outside sources such as remote server or device sensors. For example, you can have <strong>ToDoItem Repository</strong> that have methods create(), read(), update(), delete(). The methods should describe how <strong>ToDoItem</strong> can be created, deleted etc. whether they are sending HTTP requests to a remote server or SQLite transactions. If repository method returns value, it should be an instance of an entity.</p><pre>export class ToDoItemRepository {<br>    db: DB<br><br>    constructor() {<br>        this.db = open({<br>            name: &#39;todos.sqlite&#39;<br>        })<br>    }<br><br>    async create(todo: TodoItem) {<br>        const { value, completionTime, completed } = todo<br>        try {<br>           const { insertId } = await this.db.executeAsync(<br>                &#39;INSERT INTO todos (value, completionTime, completed) VALUES (?,?,?)&#39;,<br>                [value, completionTime, completed])<br>           return new TodoItem(insertId, value, completed, completionTime)<br>        }<br>        catch (er) {<br>            throw new Error(&#39;Unable to add new todo item&#39;)<br>        }<br>    }<br>    async update(todo: TodoItem){<br>    //Updating ToDoItem<br>    }<br>    <br>    //... delete, getById, and so on<br><br>}</pre><p>Another benefit of repositories is that they provide an easy way to replace React Native packages. Swapping SQLite package will only require updating a single repository, while the rest of the code will not be affected.</p><h4>Services</h4><p><strong>Services</strong> are the place where you gather data from repositories and generate resulting dataset to be passed down to <em>Presentation layer</em> (hooks). To execute methods of repositories and services we should use dependency injection, where reference of the instance will be stored inside class property. Here is the example of a service that gets all <strong>ToDoItem</strong>s from the database and stores them in a file:</p><pre>export class SaveToFile implements SaveToFileInterface {<br>    toDoItemRepo: ToDoItemRepoInterface<br>    filesystemRepo: FilesystemRepoInterface<br><br>    constructor(toDoItemRepo: ToDoItemRepoInterface, filesystemRepo: FilesystemRepoInterface) {<br>        this.toDoItemRepo = toDoItemRepo<br>        this.filesystemRepo = filesystemRepo<br>    }<br><br>    async execute(): Promise&lt;void&gt; {<br>        const todos = await this.toDoItemRepo.getAll()<br>        const content = JSON.stringify(todos)<br>        await this.filesystemRepo.writeFile(content, &#39;my_todos.txt&#39;)<br>    }<br>}</pre><p>You can also divide services into two categories based on their purpose — general services and application services. General services are likely to be executed inside another service, while application services should be executed inside the hook on the frontend side of the application.</p><p>Return value of services should also be an entity. For application services the entity may require conversion before it could be placed to state. This should be performed in presentation layer after the controller call and before setting value to sate.</p><h4>Controllers</h4><p>Controller class implements methods that passes down values from the hook to the application services and returns data back. The purpose of it is to create separation between frontend part of the app and application services and group services inside the controllers based on their domain.</p><p>Controller is also a good place to implement error handling mechanism. We can wrap application services inside try catch block and add flag isOk to be passed down to hook to handle UI changes in case of errors. Here is the controller for service that we created above.</p><pre>export class ToDoItemController extends ControllerBase {<br>   <br>    private addToDoItemService: AddTodoItemInterface<br>    private changeItemStatusService: ChangeItemStatusInterface<br>    private deleteAllService: DeleteAllInterface<br>    private getAllItemsService: GetAllItemsInterface<br>    private saveToFileService: SaveToFileInterface<br><br>    constructor(<br>        addToDoItemService: AddTodoItemInterface,<br>        changeItemStatusService: ChangeItemStatusInterface,<br>        deleteAllService: DeleteAllInterface,<br>        getAllItemsService: GetAllItemsInterface,<br>        saveToFileService: SaveToFileInterface,<br>    ) {<br>        super()<br>        this.addToDoItemService = addToDoItemService<br>        this.changeItemStatusService = changeItemStatusService<br>        this.deleteAllService = deleteAllService<br>        this.getAllItemsService = getAllItemsService<br>        this.saveToFileService = saveToFileService<br>    }<br><br>    /*<br>        Each method is wrapped inside super.execute that provides a way to handle errors.<br>    */<br><br>    addTodoItem(value: string): Promise&lt;Response&lt;TodoItem&gt;&gt; {<br>        return super.execute(() =&gt; this.addToDoItemService.execute(value))<br>    }<br><br>    changeItemStatus(id: number, completed: boolean): Promise&lt;Response&lt;TodoItem&gt;&gt; {<br>        return super.execute(() =&gt; this.changeItemStatusService.execute(id, completed))<br>    }<br><br>    deleteAll(): Promise&lt;Response&lt;void&gt;&gt; {<br>        return super.execute(() =&gt; this.deleteAllService.execute())<br>    }<br><br>    getAllItems(): Promise&lt;Response&lt;TodoItem[]&gt;&gt; {<br>        return super.execute(() =&gt; this.getAllItemsService.execute())<br>    }<br><br>    saveToFiles(): Promise&lt;Response&lt;void&gt;&gt; {<br>        return super.execute(() =&gt; this.saveToFileService.execute())<br>    }<br><br>}</pre><p>After creating controller class, we should create an instance of controller that we will then export. That controller instance is an entry point to our business logic and its methods will be called from the hooks in various parts of the app.</p><p>See <a href="https://github.com/anferrat/rn-arch-example">example repository</a> that implements this architecture pattern for a To Do List app that additionally accessing geolocation APIs, NetInfo, Database and Filesystem.</p><h3>Conclusion</h3><p>Splitting business logic into layers allows us to obtain data and execute functions like we are working with a stateless webserver. Most importantly, we can now separate code into small classes and reuse them in various parts of the app. However, unlike with a webserver, all JavaScript code in our application is executed in a single thread and complex computations in the business logic will be executed along with component re-renders. In other words, iterating over a 100k element array will freeze your JS thread the same way if you do it inside a component, or inside a service.</p><h4>Pros:</h4><ul><li>App is divided into small features and services that follow single responsibility principle</li><li>Architecture is independent from 3rd party packages.</li><li>Ease to add/remove features to the application</li><li>Allows to reuse existing codebase for new features</li><li>Makes it easier to swap native packages when needed</li></ul><h4>Cons:</h4><ul><li>Component logic is spreaded across different folders and multiple layers</li><li>Too much overhead for simple CRUD app. Instead of simply send a fetch request, you now have repository, entity, service, controller just for that. This architecture may be an overkill for smaller app with defined number of features.</li></ul><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=906fff65ebf8" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/architecture-pattern-for-react-native-applications-906fff65ebf8">Architecture pattern for React Native applications</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>