How I separate the logic and my view in React Native
Getting a small code using the single responsibility
Let’s think about how we did create our screens and components…
If we need a simple screen to show data coming from an Axios request
We will get something like this
and now, you need to add an onPress function to do any logic
Ok, there is no problem to do your logic code and view code on the same file, You can do this and there are a lot of companies and developers doing their apps exactly like this.
But, if you already do it in a big app with a lot of functions, libs, and logical calculations you probably got a big component file doing all responsibilities in just one file and if you created a test for this component, perhaps you had to create mocks for the libs, requests even your test case is just to test if the title text is rendered or not ( getByText() using testing-library for example). Ok, now you may are thinking “I can do a setup file with my mocks so, I don’t need to mock every time in each file” and I would say, yeah, you are right you can do this too.
But if I say to you that you can make your components cleaner and split the responsibility into two files and then you will have small files, with your view more testable because you won’t need to mock anything ( I’d like to say if you will do the hook tests you probably will need to mock something )
Our components will be like this:
and our new hook file will be like this:
And now we need to create a function that will connect our two files ( hook and view) to export as a screen or component that you will use normally
For it, let’s create an index file with just eight lines of code
For the last, we need to create the withHook function that will do the “magic” to wrap our component with the hook returns
And on the end, we have 3 files for the component and 1 util file that will be used for each component/screen that you will do from here.
There isn’t the best way or best pattern for all teams and projects, there are a lot of ways to create your components. And with this way you can separate your logic and view of course, if your app is small maybe it’s not needed
Once the app grows you will need to create tests and add more logic to your components and for this case maybe using the single responsibility your code will still be small and maintainable.
In the next article, I will do some tests for this Home screen and useHome the hook with the Testing library.