A Short Note – How Does The MVI Work In Android ?

Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (How does the MVI work in Android?).

In this note series, We will understand what MVI architectural pattern is, how it resolves these challenges in android.

Android architectural patterns are growing day by day. As we develop apps, we face new challenges and issues. New patterns will be discovered as we keep solving similar challenges. As Android Developers, we have MVC, MVP, and MVVM as the most commonly used patterns. All of them use an imperative programming approach. With this approach, even though most of our challenges will be resolved, we still face some challenges regarding the thread safety, maintaining states of the application.

So Let’s begin.


What is MVI architecture?

MVI stands for Model-View-Intent. This pattern has been introduced recently in Android. It works based on the principle of unidirectional and cylindrical flow inspired by the Cycle.js framework.

Let’s see what is the role of each component of MVI.

  • Model: Unlike other patterns, In MVI Model represents the state of the UI. i.e. for example UI might have different states like Data Loading, Loaded, Change in UI with user Actions, Errors, User current screen position states. Each state is stored as similar to the object in the model.
  • View: The View in the MVI is our Interfaces, which can be implemented in Activities and fragments. It means to have a container which can accept the different model states and display it as a UI. They use observable intents(Note: This doesn’t represent the Android traditional Intents) to respond to user actions.
  • Intent: Even though this is not an Intent as termed by Android from before. The result of the user actions is passed as an input value to Intents. We can say we will send models as inputs to the Intents, which can load it through Views.


How does the MVI work?

User does an action which will be an Intent → Intent is a state which is an input to model → Model stores state and send the requested state to the View → View Loads the state from Model → Displays to the user.

If we observe, the data will always flow from the user and end with the user through intent. It cannot be the other way, hence its called Unidirectional architecture. If the user does one more action, the same cycle is repeated, hence it is Cyclic.


Advantages and Disadvantages of MVI

Let’s see what are the advantages and disadvantages of MVI.


Advantages of MVI

  • Maintaining state is no more a challenge with this architecture, As it focuses mainly on states.
  • As it is unidirectional, Data flow can be tracked and predicted easily.
  • It ensures thread safety as the state objects are immutable.
  • Easy to debug, As we know the state of the object when the error occurred.
  • It’s more decoupled as each component fulfills its own responsibility.
  • Testing the app also will be easier than we can map the business logic for each state.


Disadvantages of MVI

  • It leads to lots of boilerplate code as we have to maintain a state for each user action.
  • As we know it has to create lots of objects for all the states. This makes it too costly for app memory management.
  • Handling alert states might challenge while we handle configuration changes. For example, if there is no internet we will show the snackbar, On configuration change, it shows the snackbar again as it is the state of the intent. In terms of usability, this has to be handled.


Conclusion

In this note series, we understood about what MVI architectural pattern is, how it resolves these challenges in android.

Thanks for reading! I hope you enjoyed and learned about MVI Concept in Android. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow official website and tutorials of Android as below links :

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

A Short Note – R8 vs Proguard In Android

Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (R8 vs Proguard In Android).

In this note series, we will understand about R8 vs Proguard in Android. Google released R8 as a replacement of Proguard to help developers shrink the code with the better-generated output (APK). They are considered much faster compared to Proguard.

So Let’s begin.

What is R8?

R8 is a tool that converts our java byte code into an optimized dex code. It iterates through the whole application and then it optimizes like removing unused classes, methods, etc. and runs on the compile time. It helps us to reduce the size of the build and to make our app to be more secure. R8 uses Proguard rules to modify its default behavior.

How does R8 shrinking work?

While optimizing the code, R8 reduces the code of our application, and then APK size is reduced.

To reduce the APK size, we have three different techniques:

  1. Shrinking or Tree Shaking: Shrinking is the process of removal of unreachable code from our Android project. R8 performs some static analysis to get rid of unreachable code and removes the un-instantiated object.
  2. Optimization: This is used to optimize the code for size. It involves dead code removal, unused argument removal, selective in-lining, class merging, etc.
  3. Identifier Renaming: In this process, we obfuscate the class name and other variable names. For example, if the name of the class is “MainActivity“, then it will be obfuscated to “a” or something else but smaller in size.

How to enable R8 Shrinking in our app?

R8 is present by default in our application but to enable R8 shrinking in our application, set the minifyEnabled to true in our app’s main build.gradle file.

android {
    ...
    buildTypes {
        release {
            minifyEnabled true
        }
    }
}

R8 vs Proguard

So, let’s now compare both R8 and Proguard both and see how it fares,

  • With the Android app using Gradle plugin above 3.4.0 or more the project uses R8 by default and no longer uses the Proguard to perform optimizations. But, it uses Proguard rules only.
  • R8 inlines the container classes and removes unused class, fields, and methods. Proguard reduces the app size by 8.5% and compared to R8 which reduces the code by 10%.
  • R8 has more Kotlin support compared to Proguard.
  • R8 gives better outputs than Proguard, and to do so faster than Proguard does, reducing overall build time.

So, let’s now compare how both Proguard and R8 performs.

Proguard

While using Proguard, it converts the Applications code to Java byte-code by the Java compiler. After the conversion, it is then optimized by Proguard using the rules which we have written. Then dex converts it to optimized Dalvik byte code.

This is roughly a 4 step process to convert it to Dalvik byte-code.

R8

While using R8, first the app’s code is converted to Java byte-code by the java compiler and then using R8 directly, it converts the java byte-code in Dalvik byte-code.

By using R8, it directly reduces the steps of conversion of Java byte-code to Dalvik Byte-code from 2 to 1.

  • Proguard applies 520 peephole optimizations compared to R8, which is very less. Peephole optimizations are the optimizations that are performed on a set of compiler-generated code to improve the performance of the code by making it shorter and faster.
  • In both Proguard and R8, we have to handle the reflection by writing the custom configuration.
  • R8 is faster compared to Proguard in the execution of converting the code.

Optimization Comparison between Proguard and R8

Let us discuss a few features supported by both Proguard and R8.

For example, Proguard and R8 both make the methods private in the code. Both of them also remove unused class, fields, or even methods in the project are not in use. Both of them support the simplification of Enum types. They both inline methods, merge codes, etc.

Proguard also makes the classes final whereas R8 cannot do it. But comparing R8, which is highly supported by Kotlin, optimizes the Kotlin construct which is not possible with Proguard.

Now, If you also want to enable aggressive optimization in R8 and reduce the size more, enable the following in gradle.properties.

android.enableR8.fullMode=true

Conclusion

In this note series, we understood about R8 vs Proguard in Android. We have also discussed R8 and Proguard process and optimization differences. With R8 coming as a default compile-time optimizer, it reduces the size of the app.

Thanks for reading! I hope you enjoyed and learned about R8 vs Proguard in Android. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow official website and tutorials of Android as below links :

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

A Short Note – RxJava And RxAndroid For Android

Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series.

Multi-threading in Android has always been an enormous task for engineers. RxJava has made life easy for all the Android developers using it. In this note series, we are going to discuss RxJava for Android specifically.


So Let’s begin.


What is RxJava?

RxJava is a JVM library for doing asynchronous and executing event-based programs by using observable sequences. Its main building blocks are triple O’s, Operator, Observer, and Observables. And using them we perform asynchronous tasks in our project. It makes multi-threading very easy in our project. It helps us to decide on which thread we want to run the task.

But RxJava is made for primarily any Java projects. To use RxJava in Android, we will also need RxAndroid.


What is RxAndroid?

RxAndroid is an extension of RxJava for Android, which is used only in Android application.

RxAndroid introduced the Main Thread required for Android.

To work with the multithreading in Android, we will need the Looper and Handler for Main Thread execution.

RxAndroid provides AndroidSchedulers.mainThread() which returns a scheduler and that helps in performing the task on the main UI thread that is mainly used in the Android project. So, here AndroidSchedulers.mainThread() is used to provide us access to the main thread of the application to perform actions like updating the UI.

In Android, updating UI from background thread is technically not possible, so using AndroidSchedulers.mainThread() we can update anything on the main thread. Internally it utilizes the concept of Handler and Looper to perform the action on the main thread.

RxAndroid uses RxJava internally and compiles it. But while using RxAndroid in our project we still add the dependency of RxJava to work with like,

implementation 'io.reactivex.rxjava3:rxjava:3.0.0'
implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'


Use-Cases in Android

RxJava has the power of operators and as the saying goes by, “RxJava has an operator for almost everything“.


Case 1:

Consider an example, where we want to do an API call and save it to some storage/file. It would be a long-running task and doing a long-running task on the main thread might lead to unexpected behavior like App Not Responding.

So, to do the above-mentioned task, we might think to use AsyncTask as our go-to solution. But with Android R, AsyncTask is going to be deprecated, and then libraries like RxJava will be the solution for it.

Using RxJava over AsyncTask helps us to write less code. It provides better management of the code, as using AsyncTask might make the code lengthy and hard to manage.


Case 2:

Consider a use-case where we might want to fetch user details from an API and from the user’s ID which we got from the previous API we will call another API and fetch the user’s friend list.

Doing it using AsyncTask we might have to use multiple Async task and manage the results in was way where we want to combine all the AsyncTask to return the result as a single response.

But using RxJava, we can use the power of zip operator to combine the result of multiple different API calls and return a single response.


Case 3:

Consider an example of doing an API call and getting a list of users, and from that, we want only the data which matches the given current condition.

A general approach is to do the API call, and from the Collection, we can then filter the content of that specific user based on the condition and then return the data.

But using RxJava we can directly filter out the data while returning the API response by using the filter operator, and we do all of this by doing the thread management.

These are a few use cases to understand RxJava for Android and why we need RxAndroid in our project.


Conclusion

In this note series, we understood about the RxJava and RxAndroid for Android. We discussed a few use cases to understand RxJava for Android and why we need RxAndroid in our project.

Thanks for reading ! I hope you enjoyed and learned about the RxJava and RxAndroid Concepts for Android. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow official website and tutorials of Android as below links :

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

A Short Note – How Redux Works?

Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (How Redux Works?).

In this note series, we will understand about the Redux work flow concepts in ReactJS.

So Let’s begin.

Redux

Redux is just one variation of a whole trend in UI architecture called : Unidirectional User Interface Architecture.

For example, there is Flux (Redux is just a variation of Flux), Cycle.js, MobX, and Elm has its own implementation of that architecture.

As stated from the Redux motivation, Redux tries to make: “state mutation predictable”, and it tries to achieve that by the following:

  • Have one single source of truth (from the state)
  • States are read only and immutable.
  • Changes are made with pure functions.

Redux Work Flow

There is a wonderful diagram that describes the flow in Redux.

(we use This diagram as an educational and information purpose).

This is the data flow:

  1. Models/states in the application should reside in a container called “Store”. Even we can have many stores in an application, but Redux differs from others (like Flux) by leaning toward one store.
  2. Communication to the store should happen through one gate, which is a function called “dispatch”.
  3. Anything wants to modify the state should dispatch “Actions” which are a simple JavaScript objects that describe what we want to modify and the new data.
  4. The Store receives the actions and pass it to “Reducers” which are pure functions that modify the store’s state and produce a new state.
  5. Store’s state is immutable, and any modification will generate always a new state.
  6. The Store will notify any subscribers about new changes.
  7. UI render itself, using pure functions, taking the store’s state as input parameter.
  8. Asynchronous network calls will modify the store through actions as everything else.

Why Redux is better ?

Redux solves many problems:

  • Because we use pure functions everywhere, so always the output is deterministic, and we have deterministic UI.
  • Time Travelling: Because we change the state through actions which are pure JavaScript objects, which means we can at any moment re-create the state from scratch if we keep a log of those actions, so time-travelling will be a breath.
  • Logging actions, we can know who modify the state, and when exactly.
  • Collaborative programs like (google docs) can be achieved easily by sending Actions on the wire and recreate them there.
  • Easy debugging, by logging all actions on production we can re-create the whole situation.
  • Deterministic UI, because UI rendering using pure function, and the same input will always generate the same output.
  • Unit test is so easy, because we are testing pure functions for UI and state mutation.

Conclusion

In this note series, we understood about the Redux Work Flow Concepts in ReactJS. We discussed that how Redux works and why it is better.

Thanks for reading! I hope you enjoyed and learned about Redux Work Flow Concepts in ReactJS. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe to the blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow official website and tutorials of React as below links :

If you have any comments, questions, or think I missed something, leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

A Short Note – Understanding React Redux Concepts

Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (Understanding React Redux Concepts).

In this note series, we will understand about the React Redux concepts in ReactJS.

So Let’s begin.

What were the Major Problems With MVC Framework ?

Following are some of the major problems with MVC framework:

  • DOM manipulation was very expensive
  • Applications were slow and inefficient
  • There was huge memory wastage
  • Because of circular dependencies, a complicated model was created around models and views

What is Flux ?

Flux is an architectural pattern which enforces the uni-directional data flow. It controls derived data and enables communication between multiple components using a central Store which has authority for all data. Any update in data throughout the application must occur here only. Flux provides stability to the application and reduces run-time errors.

What is Redux?

Redux is one of the hottest libraries for front-end development in today’s marketplace. It is a predictable state container for JavaScript applications and is used for the entire applications state management. Applications developed with Redux are easy to test and can run in different environments showing consistent behavior.

What are the three principles that Redux follows?

  1. Single source of truth: The state of the entire application is stored in an object/ state tree within a single store. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.
  2. State is read-only: The only way to change the state is to trigger an action. An action is a plain JS object describing the change. Just like state is the minimal representation of data, the action is the minimal representation of the change to that data. 
  3. Changes are made with pure functions: In order to specify how the state tree is transformed by actions, you need pure functions. Pure functions are those whose return value depends solely on the values of their arguments.

The Main Components of Redux

Redux is composed of the following components:

  1. Action – It’s an object that describes what happened.
  2. Reducer –  It is a place to determine how the state will change.
  3. Store – State/ Object tree of the entire application is saved in the Store.
  4. View – Simply displays the data provided by the Store.

How is Redux different from Flux?

FluxRedux
1. The Store contains state and change logic1. Store and change logic are separate
2. There are multiple stores2. There is only one store
3. All the stores are disconnected and flat3. Single store with hierarchical reducers
4. Has singleton dispatcher4. No concept of dispatcher
5. React components subscribe to the store5. Container components utilize connect
6. State is mutable6. State is immutable
Flux Vs Redux

What are the advantages of Redux?

Advantages of Redux are listed below:

  • Predictability of outcome – Since there is always one source of truth, i.e. the store, there is no confusion about how to sync the current state with actions and other parts of the application.
  • Maintainability – The code becomes easier to maintain with a predictable outcome and strict structure.
  • Server-side rendering – You just need to pass the store created on the server, to the client side. This is very useful for initial render and provides a better user experience as it optimizes the application performance.
  • Developer tools – From actions to state changes, developers can track everything going on in the application in real time.
  • Community and ecosystem – Redux has a huge community behind it which makes it even more captivating to use. A large community of talented individuals contribute to the betterment of the library and develop various applications with it.
  • Ease of testing – Redux’s code is mostly functions which are small, pure and isolated. This makes the code testable and independent.
  • Organization – Redux is precise about how code should be organized, this makes the code more consistent and easier when a team works with it.

Conclusion

In this note series, We understood about the React Redux Concepts in ReactJS.

Thanks for reading ! I hope you enjoyed and learned about React Redux Concepts in ReactJS. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe to the blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow official website and tutorials of React as below links :

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

A Short Note – Shadow DOM vs Virtual DOM In ReactJS

Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (Shadow DOM vs Virtual DOM In ReactJS).

In this note series, we will understand about the difference between Shadow DOM and Virtual DOM in ReactJS. We discuss the key differences between the virtual DOM and the shadow DOM.

So Let’s begin.

The shadow DOM and virtual DOM are both fundamental to progressive web frameworks like Angular, Vue, and React. While the shadow DOM encapsulates the implementation of custom web components, the virtual DOM is used to differentiate changes and more effectively re-render UIs.


What is the Virtual DOM ?

The virtual DOM is an in-memory representation of the real DOM. Popular UI libraries like React and Vue implement a virtual DOM to more efficiently re-render UI components based on a “diffing” process. By comparing changes between a virtual DOM and the real DOM, rendering engines can more efficiently determine what actually needs to be updated. This avoids unnecessary redrawing of DOM nodes as only elements that have changed are redrawn. Without the virtual DOM, every element is redrawn regardless of whether or not it has changed. This adds a huge performance boost to DOM manipulation since redrawing elements is an expensive process.


What is the Shadow DOM ?

The shadow DOM is a way of encapsulating the implementation of web components. Using the shadow DOM, you can hide the implementation details of a web component from the regular DOM tree. A popular example is the HTML5 slider input. While the regular DOM recognizes this as a simple <input/> tag, there is underlying HTML and CSS that make up the slide feature. This sub-tree of DOM nodes is hidden from the main DOM to encapsulate the implementation of the HTML5 slider. Additionally, the CSS properties for the slider are isolated from the rest of the DOM. This provides an isolated scope that prevents the component’s styles from overriding other CSS properties defined elsewhere.

The isolated scope provided by the shadow DOM results in performance benefits. By isolating the CSS properties for a custom web component, the browser can more accurately determine what needs to be updated when the DOM is manipulated.


Shadow DOM vs Virtual DOM

While the shadow DOM and virtual DOM are seemingly similar in their creation of separate DOM instances, they are fundamentally different. The virtual DOM creates an additional DOM. The shadow DOM simply hides implementation details and provides isolated scope for web components.


Conclusion

In this note series, We understood about the Shadow DOM vs Virtual DOM In ReactJS. We conclude that both the shadow DOM and virtual DOM have played a key role in the development of progressive web frameworks. While both add performance benefits, the virtual DOM is used to efficiently redraw UIs whereas the shadow DOM encapsulates the implementation of custom web components.

Thanks for reading ! I hope you enjoyed and learned about Shadow DOM Vs Virtual DOM Concepts in ReactJS. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe to the blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow official website and tutorials of React as below links :

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

A Short Note – Stateless Component vs Pure Component in React Application

Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (Stateless Component vs Pure Component in React Application).

In this note series, we will understand about the difference between Stateless Component and Pure Component in React Application. We will be discussing how both components compare performance wise, developer experience and how both will fit into our ReactJS production project.


So Let’s Begin.


Stateless Component

STATELESS COMPONENT declared as a function that has no state and returns the same markup given the same props.

A quote from the React documentation:

These components must not retain internal state, do not have backing instances, and do not have the component lifecycle methods. They are pure functional transforms of their input, with zero boilerplate. However, we may still specify .propTypes and .defaultProps by setting them as properties on the function, just as we would set them on an ES6 class.


Pure Component

PURE COMPONENT is one of the most significant ways to optimize React applications. The usage of Pure Component gives a considerable increase in performance because it reduces the number of render operation in the application.


Example

Let’s look at the performance aspect of both components.

class Welcome extends React.PureComponent {  
  render() {
    return <h1>Welcome</h1>
  }
}

Hello = () => {
  return <h1>Hello</h1>;
}

So above there is an example of a very simple Welcome Pure Component and Hello Stateless Component. When we use these two in our Parent Component, we will see Hello will re-render whenever Parent Component will re-render but Welcome Component will not.

This is because PureComponent changes the life-cycle method shouldComponentUpdate and adds some logic to automatically check whether a re-render is required for the component. This allows a PureComponent to call the method render only if it detects changes in state or props.


When to use Pure Components?

Suppose we are creating a dictionary page in which we display the meaning of all the English words starting with A. Now we can write a component which takes a word and its meaning as props and return a proper view. And suppose us using pagination to display only 10 words at a time and on scroll asking for another 10 words and updating the state of the parent component. Pure Components should be used in this case as  it will avoid rendering of all the words which rendered in previous API request.

Also in cases where we want to use lifecycle methods of component then we have to use Pure components as stateless components don’t have lifecycle methods.


When to use Stateless Components?

Suppose we want to create a label with some beautiful UI which will be used to rate the credibility of a profile like BEGINNER, MODERATE, EXPERT. Since its a very small component whose re-render will hardly make any difference and creating a new component for such a small case will be time-consuming. Also if we keep making components for very small-small view, soon we will end up with so many components and it will be hard to manage when working with a big project. Also always keep in mind Pure Component comes with peculiarities of the shallowEqual.


Conclusion

In this note series, We understood about the difference between Stateless Component and Pure Component in React application.

Thanks for reading ! I hope you enjoyed and learned about the Stateless Component and Pure Component differences in React application. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe to the blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow official website and tutorials of React as below links :

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

A Short Note – How to Improve the Performance of React Native App?

Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (How to Improve the Performance of React Native App?).

In this note series, we will understand about the pro tips to improve the performance of the React Native app. There are so many ways to do this but here we will discuss few most preferred ways as below:

  • Use of shouldComponentUpdate method of react-native life cycle
  • Pure Components of React
  • Use Memo from Hooks API
  • Build the module with native whenever it is possible
  • Remove the console logs before building the application
  • Reduce Application size


So Let’s begin.


1. Use of shouldComponentUpdate method of react-native life cycle

Using shouldComponentUpdate method, we can reduce un-necessary re-rendering of components.

shouldComponentUpdate returns the boolean value and according to that components will re-render. For example, if it returns true then it will re-render and if it returns false then it will not re-render component.

So, on state update or on new props to the component, this method will be called with two arguments called nextState and nextProps. So, we can compare the new props and state with the previous ones. And according to our business logic requirements, we can use the boolean to render the component again.


2. Pure Components of React

The pure component of React helps to render only the specific props that have been changed or the state has updated.

For example, if we are using a flatlist which is rendering 1000 rows. Now, on every re-render, that 1000 data will be rendered again.

Using Flatlist in the pure component, we can ensure that only the change on required props components will re-render again.


3. Use Memo from Hooks API

React Hooks provide the life cycle of components to functions.

Memo from react helps to do a shallow comparison on upcoming changes. So, it allows re-rendering functions only if the props get changed.


4. Build the module with the native driver whenever it is possible

Here, We are not talking about not using React Native. Sometimes, we have to use some features which can be done by the native more efficiently. We build that module in native one and can use the feature from the React Native by creating a bridge.


5. Remove the console logs before building the application

It has been identified that the console logs are taking some amount of time for logging purposes. So, it is good to use at the time of development but in the production build, it should be removed which will help to improve the performance of the app which we will realize while using it.


6. Reduce Application size

In React Native, we use external libraries and components form libraries so it impacts application size.

To reduce the size, we have to optimize the resources, use ProGaurd, create different app sizes for different device architectures, and make sure to compress the graphics elements, i.e. images.

The components on the JavaScript side use a bridge to communicate with the Native side. Reduce the load on the bridge and improve the app’s performance.


Conclusion

In this note series, we understood about the pro tips to improve the performance of the React Native app.

Thanks for reading! I hope you enjoyed and learned about the React Native app Performance Improvement pro tips. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe to the blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow official website and tutorials of React Native as below links :

If you have any comments, questions, or think I missed something, leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

A Short Note – Functional vs Class Components in React Native

Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (Functional vs Class Components in React Native).

In this note series, we will understand about the difference between Functional and Class Components in React Native.

So Let’s begin.

In React Native, there are two main types of components that make up an application: functional components and class components. These are structured the same as they would be in a regular React app for the web.


Class Components vs Functional Components


1. Syntax

Class components are JavaScript ES2015 classes that extend a base class from React called Component and create a render function that returns a React element. This requires more code as well.

The Class Component in React Native

class App extends Component {
    render () {
        return (
            <Text>Hello World!</Text>
        )
    }
}
export default App;

A Functional Component looks like a plain JavaScript function and are sometimes called stateless components.

The Functional Component in React Native

const App = () =>{
	return (
	  <Text>Hello World!</Text>
	)
}
export default App;


2. State

In Class components, there is a way to store and manage state built in to React Native. This gives the class App access to the React life cycle methods like render as well as state/props functionality from the parent. While managing the state in classes, we use setState and this.state to set and get the state, respectively.

State in Class Component

mport React from 'react';
import {Text, View} from 'react-native';

class App extends React.Component {
	constructor(props){
		super(props);
		this.state = { value:0};
		setInterval(() =>{
			this.setState({ value: this.state.value + 1});
		}, 1000);
	}

	render() {
		return (
			<View>
				<Text>{'State Value =>' + this.state.value}</Text>
			</View>
		);

	}
}

export default App;

But in the functional component, we have useState hook after the update of React 16.8. They don’t manage their own state by React Native.

State in Functional Component

import React, { useState } from 'react';
import {Text, View} from 'react-native';

const App = () => {
		let [value, setValue] = useState(0);
		
		setInterval(() =>{
			setValue(value + 1);
		}, 1000);
	
		return (
			<View>
				<Text>{'State Value =>' + value}</Text>
			</View>
		);
};

export default App;


3. Lifecycle Methods/Hooks

Another most important difference in Class and Functional Component is the life cycle methods, or we can say Lifecycle Hooks. We all know how important is the Lifecycle methods while developing any React Native application. Life cycle methods give us the power to control the data and application flow on different activities. We are very much familiar with the class component Lifecycle methods but in case of Functional Components we have to manage all this with the help of useEffect hook.

Example of Lifecycle Methods for Class Component

import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    }
  }

  componentDidMount() {
    const interval = setTimeout(() => {
      this.setState({ count: this.state.count + 1 });
    }, 1000);
    return () => {
      clearInterval(this.interval);
    }
  }

  render() {
    return (
      <View style={styles.container}>
        <Text> Count incremented {this.state.count} times</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Example of useEffect Hook for Functional Component

import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default function App() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount
  useEffect(() => {
    const interval = this.setTimeout(() => {
      setCount(count + 1);
    }, 1000);
    return () => {
      clearInterval(this.interval);
    }
  }, []);

  return (
    <View style={styles.container}>
      <Text> Count incremented {count} times</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});


Conclusion

In this note series, we understood about the difference between Functional and Class Components in React Native. We conclude that :

  • Class components are used as container components to handle state management and wrap child components.
  • Functional components are just used for display purposes – these components call functions from parent components to handle user interactions or state updates. 

Thanks for reading! I hope you enjoyed and learned about Functional Vs Class Components Concepts in React Native. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe to the blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow official website and tutorials of React Native as below links :

If you have any comments, questions, or think I missed something, leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

A Short Note – 7 Quick Valuable Commands To Improve React Native Development

Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (7 Quick Valuable Commands To Improve React Native Development).

In this note series, we will learn about seven quick valuable commands which is commonly used and helps to improve React Native Development to start developing iOS and Android apps.


So, Let’s begin.


1. Starting a new project

There are different ways, we can bootstrap a react native application. You can use Expo or create-react-native-app (which in turns uses Expo-Cli) to start our new project, but with this method, we are in more control of what happened in our project and can communicate, tweak and write our own modules with native libraries for iOS and Android mobile platform.

react-native init [PROJECT-NAME]
cd [PROJECT-NAME]


2. Run app in Android Emulator

This command is self explanatory and as it says it will start the Android emulator and install the app you just created. You need to be in the root of the project to run this command.

react-native run-android


3. Run app in iOS Emulator

This command do exactly the same as react-native run-android but instead of the Android emulator, it opens the iPhone simulator.

react-native run-ios


4. Link dependencies to native projects

Some libraries have dependencies that need to be linked in the native code generated for React Native. If something doesn’t work after you installed a new library, maybe is because you skip this step.

react-native link [LIBRARY-NAME]


5. Clear bundle

If something don’t run as expected, maybe you need to clear and create a new bundle with this command.

watchman watch-del-all


6. Support decorators

JSX doesn’t support decorators by default so you need to install the Babel plugin to make it work.

npm install babel-plugin-transform-decorators-legacy --save
npm install babel-plugin-transform-class-properties --save


7. Export APK to run in device

With the following commands you will have and unsigned apk so you can install and share with your colleagues for testing purposes. Just remember that this apk is not ready to upload to the App Store or production. You will find your fresh apk in android/app/build/outputs/apk/app-debug.apk.


Bundle debug build

react-native bundle --dev false --platform android --entry-file index.android.js --bundle-output ./android/app/build/intermediates/assets/debug/index.android.bundle --assets-dest ./android/app/build/intermediates/res/merged/debug


Create debug build

cd android
./gradlew assembleDebug


Conclusion

In this note series, we understood about seven quick valuable commands which is commonly used in React Native Development.

Thanks for reading! I hope you enjoyed and learned about React Native Commands List. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe to the blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow official website and tutorials of React Native as below links :

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

Exit mobile version