JavaScript – Understanding DOM Manipulation

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about JavaScript popular DOM Manipulation Concepts. When developing a front-end application, one of the most expected things a programmer wants to do is to manipulate the document structure in some way. It happens by using the Document Object Model (DOM), which is a set of APIs for controlling HTML and styling information.

For better understanding about the concepts, We will discuss the following details related to DOM manipulation using JavaScript:

  • What is DOM?
  • DOM Terminologies
  • How to access DOM elements using JavaScript?
  • How to manipulate DOM elements using JavaScript?

A famous quote about learning is :

” Anyone who stops learning is old, whether at twenty or eighty. Anyone who keeps learning stays young. “

So, Let’s start.

What is DOM?

 DOM is a data representation of the objects in the HTML and XML pages. The document loaded in your browser is represented by a document object model. Moreover, it is a “tree structure” representation created by the browser that enables the HTML structure to be easily accessed by programming languages. Additionally, the DOM represents the document as nodes and objects. In this way, programming languages can connect to the page. Furthermore, a simple structure of a web page DOM will look like below:

DOM Terminologies

Before starting working on the DOM, we should understand the following terminologies related to DOM:

  • Element node: It represents any element that exists in the DOM.
  • Root node: This is the top node in the tree, which in the case of HTML, is always the “HTML” node.
  • Child node: This is a node that is directly inside another node. For example, <h2> is a child of  <body> in the above example.
  • Descendant node: This is a node that exists anywhere in the hierarchy of another node. For example, <h2> is a descendant of <html> in the above example.
  • Parent node: This is a node that has another node inside it. For example, <body> is the parent node of  <h2> in the above example.
  • Sibling nodes: The nodes which sit on the same level in the DOM tree. For example, <h2> and  <p> are siblings in the above example.
  • Text node: This is a node that contains a text string.

As we are now clear about the fundamental terminologies used in a document, let’s move to the next section to understand how the DOM elements can be accessed using JavaScript.

How to access DOM elements using JavaScript?

A webpage in JavaScript is a document, and JavaScript provides an object “document,” which designates the complete webpage. Moreover, the document object provides various properties and methods to access and manipulate the web elements loaded on the page. To identify and access the DOM elements, JavaScript uses three ways:

  • Accessing elements By ID
  • Accessing elements By TagName
  • Accessing elements By className

Let’s understand the details of each of these ways in the following sections:

1. Accessing elements By ID:

JavaScript can find HTML elements in the DOM based on the “id” of the element. The document object provides a method “getElementById()” to accomplish this task. Moreover, its syntax looks like below: 

Syntax :

document.getElementById(“IDName”);

Let’s understand the usage of the “getElementById” method with the help of the following code snippet.

<body>
 Demonstrating getElementById in javascript:    </br>
    <b id="bold">Development Tools Tutorial</b>
 
     <script type="text/javascript">
    // Get the element by Id and update text on that
     document.getElementById("bold").innerHTML = "Development Tools";
     </script>
    </body>
</html>

In the above example, we can see that element by id “bold” has been found. In addition to that, we also changed its attribute innerHTML to Development Tools.

2. Accessing a DOM element By TagName:

JavaScript can find the elements in the HTML based on the “tagName” and return an array of matching nodes. The inbuilt function, of document object, available for this is getElementByTagName(). Additionally, its syntax looks like below:

Syntax :

document.getElementByTagName(“tagName”);

Let’s understand the usage of “getElementByTagName” method with the help of following code snippet:

<html>    
 <body>
 Demonstrating getElementByTag in javascript:    </br>
    <b>Development Tools Tutorial</b>
 
     <script type="text/javascript">
    // Get the element by tag <b> and update text on that
     document.getElementsByTagName("b")[0].innerHTML = "Development Tools";
     </script>
    </body>
</html>

In the above example, we can see that the element by HTML tag “<b>” has been found. Additionally, we changed its attribute innerHTML to Development Tools.

3. Accessing a DOM element By ClassName:

JavaScript can find the element in the HTML based on the className attribute of the element and returns an array of matching nodes. The inbuilt function available in this operation is getElementByClassName(). Additionally, its syntax looks like below:

Syntax :

document.getElementByClassName(“ClassName”);

Let’s understand the usage of “getElementByClassName” method with the help of following code snippet:

<html>    
 <body>
 Demonstrating getElementsByClassName in javascript:    </br>
    <b class="bold">Development Tools Tutorial</b>
 
     <script type="text/javascript">
    // Get the element by className "bold" and update text on that
     document.getElementsByClassName("bold")[0].innerHTML = "Development Tools";
     </script>
    </body>
</html>

In the above example, we can see that element by className “bold” has been found. Additionally, we changed its attribute innerHTML to Development Tools.

How to manipulate DOM elements using JavaScript?

Apart from accessing the elements, JavaScript provides some methods and properties which can manipulate or change the values of the DOM elements. Few of those methods and properties are:

  • write
  • innerHTML
  • attributeName
  • Style.property
  • setAttribute
  • createElement and appendChild
  • removeChild
  • replaceChild

Let’s discuss all of these methods and properties in detail in the below sections:

1. write :

This method writes new elements or text to the HTML page. Additionally, its syntax looks like below:

Syntax:

document.write(“data”);

Let’s understand the usage of “write()” method with the help of following code snippet:

<html>
 
   <body>  
 
      Demonstrating document's write function in javascript:
 
   </br>
 
      <script type = "text/javascript">
 
         document.write("Development Tools Tutorials");
 
         document.write("</br>");
 
         document.write("<b>JavaScript Tutorial</b>");
 
      </script>   
 
   </body>
 
</html>

In the above example, we use the write function to add a text as well as to add a new HTML element.

2. innerHTML :

It is a property that we use to get or set the HTML or XML markup contained within the element. Also, its syntax looks like below:

Syntax:

node.innerhtml = “changingText”;

Where,

node: is any web element that can be found on the web page using document.getElementBy<Id/tagName/className>.

Let’s understand the usage of “innerHTML” property with the help of following code snippet:

<html>
 
   <body>  
 
      Demonstrating innerHTML property in javascript
 
   </br>
 
   <b id="example">JavaScript Tutorial</b>
 
      <script type = "text/javascript">
 
         document.getElementById("example").innerHTML="Development Tools";
 
      </script>   
 
   </body>
 
</html>

In the above example, we can see that the innerHTML property updates the text of the HTML element.

3. attributeName :

We use his property is used to get and update the value of an attribute of an HTML element. Additionally, its syntax looks like below:

Syntax :

node.atrributeName = value;

Where,

node: is any web element that can be found on the web page using document.getElementBy<Id/tagName/className>.

Let’s understand the usage of “attributeName” property with the help of following code snippet:

<html>
 
   <body>  
 
      Demonstrating attributeName property in javascript
 
   </br>
 
   <b id="example">JavaScript Tutorial</b>
 
      <script type = "text/javascript">
 
         // Update the "id" of the element to "demo" which has "id" as "example"
         document.getElementById("example").id="demo";
 
         
         // Get the element with "id" as "demo" and update its innerHTML text
         document.getElementById("demo").innerHTML="Development Tools";
 
      </script>   
 
   </body>
 
</html>

In the above example, the element is first changed from “example” to “demo” and then based on id “demo,” we are manipulating the text of the element.

4. Style.property :

We use this property to set or edit the existing style properties of an HTML tag. Also, its syntax looks like below:

Syntax:

node.Style.attribute = value;

Where,

node: is any web element that can be found on the web page using document.getElementBy<Id/tagName/className>.

Let’s understand the usage of “Style.attribute” method with the help of following code snippet:

<html>
 
   <body>  
 
      Demonstrating updating style properties in javascript
 
   </br>
 
   <b id="example">JavaScript Tutorial</b>
 
      <script type = "text/javascript">
 
         document.getElementById("example").style.color = "red";
 
      </script>   
 
   </body>
 
</html>

In the above example, the style attribute “color” has been updated to “red.”

5. setAttribute :

We use this function to create or update an attribute for the existing HTML element. Additionally, its syntax looks like below:

Syntax :

node.setAttribute(attributeName, attributeValue);

Where,

node: is any web element that can be found on the web page using document.getElementBy<Id/tagName/className>.

Let’s understand the usage of “setAttribute()” method with the help of following code snippet:

<html>
 
   <body>  
 
      Demonstrating setAttribute function in javascript
 
   </br>
 
   <b>JavaScript Tutorial</b>
 
      <script type = "text/javascript">
 
         document.getElementsByTagName("b")[0].setAttribute("id","example");
 
         document.getElementById("example").innerHTML="Development Tools";
 
      </script>   
 
   </body>
 
</html>

In the above example, the element is first added a new attribute “id” with value “example” to the <b> tagged HTML element and then based on id “example,” we are manipulating the text of the element.

6. createElement and appendChild :

This createElement() method is used to create a new element in the HTML DOM. Once the creation of element happens, it can append to a parent element using the appendChild() method. Moreover, its syntax looks like below: 

Syntax:

// Create a new node
var node = document.createElement(tagName);


// Append the node to parent
document.parentTag.appendChild(node);

Let’s understand the usage of “createElement() and appendChild()  method with the help of following code snippet:

<html>

   <body>  

      Demonstrating createElement function in javascript

   </br>

   <b>JavaScript Tutorial</b>

      <script type = "text/javascript">

         var b = document.createElement("a");

         b.innerHTML="ClickME";

         document.body.appendChild(b);

      </script>   

   </body>

</html>

In the above example, we created a new “anchor” element with the help of the “createElement” method and then appended the element to the document’s <body> element. Hence, it displays on the HTML page.

7. removeChild :

This function removes an HTML element from the document. Also, its syntax looks like below:

Syntax:

node.removechild(childNode);

Where,

node: is any web element that can be found on the web page using document.getElementBy<Id/tagName/className>.

Let’s understand the usage of “removeChild()” method with the help of following code snippet:

<html>

   <body>  

      Demonstrating removeChild function in javascript

   </br>

   <b>TOOLS QA</b>

   </br>

   <b id="demo">JavaScript Tutorial</b>

      <script type = "text/javascript">

        document.body.removeChild(document.getElementById("demo"));

      </script>   

   </body>

</html>

In the above example, we removed the HTML element, which was having “id” as “demo,” due to which the value “JavaScript Tutorial” could not print on the webpage.

8. replaceChild :

The replaceChild() method replaces a child node with a new node. The new node could be an existing node in the document, or you can create a new node. Additionally, its syntax looks like below: 

Syntax:

node.replaceChild(newnode, oldnode);

Where,

node: is any web element that can be found on the web page using document.getElementBy<Id/tagName/className>.

Let’s understand the usage of “replaceChild()” method with the help of following code snippet:

<html>
   <body>  
      Demonstrating replaceChild function in javascript: </br>
 
      <ul id="myList"><li>Coffee</li><li>Tea</li><li>Milk</li></ul>

      <button onclick="replaceListValue()">Replace first value of list</button>

      <script type = "text/javascript">
         
         function replaceListValue() {
            // Create a new list element
            var newListElement = document.createElement("li");
            var textNode = document.createTextNode("Water");
            newListElement.appendChild(textNode);

            // Replace the first element of list by the newly created element
            var list = document.getElementById("myList");
            list.replaceChild(newListElement, list.childNodes[0]);
         }
    
      </script>   
 
   </body>
 
</html>

In the above example, we replace the first element of the list on the click of the button. The replaceChild method also achieves the same.

That’s all about in this article.

Conclusion

In this article, We understood about JavaScript Fundamental Concept DOM Manipulation. We conclude that :

  • The document loaded in a browser is represented by the document object model (DOM). Moreover, it is a data representation of the objects in the HTML page.
  • Also, the ID, Tag Name, or Class Name of the HTML elements can access the DOM elements.
  • In addition to the above, JavaScript also provides various methods such as setAttribute, createElement, appendChild, removeChild, etc. Moreover, we can use them to manipulate/change multiple HTML elements within the page at run time.

Thanks for reading !! I hope you enjoyed and learned about JavaScript Fundamental Concept DOM Manipulation. 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 and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

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 !!???

Android – An Overview of Room Persistent Library

Hello Readers, CoolMonkTechie heartily welcomes you in this article (An Overview of Room Persistent Library).

In this article, we will learn about Android Room Persistent Library Overview. We will try to understand the basics of Room, how to use it, major components in Room and type converters in Room.

For better understanding about Android Room Persistent Library, we will discuss the below points:

  • What is Room in Android ?
  • What are the advantages of Room in Android Application ?
  • How to use it in our Project or Application?
  • What is major components of Room in Android ?
  • Type Converters in Room

A famous quote about learning is :

He who learns but does not think, is lost! He who thinks but does not learn is in great danger.

So, Let’s start.

What is Room in Android ?

Room is an Android persistence library, which is part of Google’s Android Jetpack project.

According to the Android Documentation, “Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.

The library helps us create a cache of our app’s data on a device that’s running our app. This cache, which serves as our app’s single source of truth, allows users to view a consistent copy of key information within our app, regardless of whether users have an internet connection.

It means that Apps that handle significant amounts of structured data can benefit from persisting that data locally. The most common use case is to cache relevant pieces of data. That way, when the device cannot access the network, the user can still browse that content while they are offline. Any user-initiated content changes are then synced to the server after the device is back online.

What is the advantages of Room in Android Application ?

There are multiple advantages of using Room as compared to other alternate solutions like SQLiteOpenHelper:

  • Compile-time verification of queries.
  • Reduces boilerplate code.
  • Easy to understand and use.
  • Easy integration with RxJava, LiveData and Kotlin Coroutines.

How to use it in our Project or Application?

To use Room in your app, add the following dependencies to our app’s build.gradle file:

dependencies {
  def room_version = "2.2.5"

  implementation "androidx.room:room-runtime:$room_version"
  annotationProcessor "androidx.room:room-compiler:$room_version" // For Kotlin use kapt instead of annotationProcessor

  // optional - Kotlin Extensions and Coroutines support for Room
  implementation "androidx.room:room-ktx:$room_version"

  // optional - RxJava support for Room
  implementation "androidx.room:room-rxjava2:$room_version"

  // optional - Guava support for Room, including Optional and ListenableFuture
  implementation "androidx.room:room-guava:$room_version"

  // Test helpers
  testImplementation "androidx.room:room-testing:$room_version"
}

Note: For Kotlin-based apps, make sure we use kapt instead of annotationProcessor. We should also add the kotlin-kapt plugin.

What is major components of Room in Android ?

There are 3 major components in Room:

  • Database: Contains the database holder and serves as the main access point for the underlying connection to our app’s persisted, relational data.
  • Entity: Represents a table within the database.
  • DAO: Contains the methods used for accessing the database.

Our application uses the Room database to get the data access objects, or DAOs, associated with our database. The app then uses each DAO to get entities from the database and save any changes to those entities back to the database. Finally, the app uses an entity to get and set values that correspond to table columns within the database.

This relationship among the different components of Room appears in Figure 1:

1. Database

As mentioned earlier, it contains the database holder and serves as the main access point for the underlying connection to our app’s persisted, relational data. The class that’s annotated with @Database should satisfy the following conditions:

  • Be an abstract class that extends RoomDatabase.
  • Include the list of entities associated with the database within the annotation.
  • Contain an abstract method that has 0 arguments and returns the class that is annotated with @Dao.

At runtime, you can acquire an instance of Database by calling Room.databaseBuilder() or Room.inMemoryDatabaseBuilder().

@Database(entities = arrayOf(User::class), version = 1)
abstract class UserDatabase : RoomDatabase() {
  abstract fun userDao(): UserDao
}

To get an instance of the database, you can use the following method:

val db = Room.databaseBuilder(
    applicationContext,
    UserDatabase::class.java, "users-db"
    ).build()

We have noted that :

  • If our app runs in a single process, we should follow the singleton design pattern when instantiating an AppDatabase object. Each RoomDatabase instance is fairly expensive, and we rarely need access to multiple instances within a single process.
  • If our app runs in multiple processes, include enableMultiInstanceInvalidation() in our database builder invocation. That way, when we have an instance of AppDatabase in each process, we can invalidate the shared database file in one process, and this invalidation automatically propagates to the instances of AppDatabase within other processes.”

2. Entity

An Entity represents a table within a database. This class is annotated with @Entity annotation. Data members in these class represent the columns within a table. For example :

@Entity
data class User(
  @PrimaryKey val uid: Int,
  @ColumnInfo(name = "first_name") val firstName: String?,
  @ColumnInfo(name = "last_name") val lastName: String?
)
  • All the fields in an entity must either be public or have getter & setter methods.
  • Entity class should have an empty constructor (if all fields are accessible) or a parametrised constructor which takes all the fields. Room can also use partial constructors.
  • Each entity class must have at least one primary key. We can use either @PrimaryKey annotation to define single field primary key or primaryKeys attribute of @Entity annotation for multiple fields. We can also use autoGenerate property of @PrimaryKey annotation to automatically assign primary keys.
@Entity(primaryKeys = arrayOf("firstName", "lastName"))
  • By default, Room uses the class name as the database table name. If we want the table to have a unique name, set the tableName property of the @Entity annotation. Similarly, we can use the name property of the @ColumnInfo annotation for defining the name of columns.
@Entity(tableName = "users")
  • If we don’t want to persist in any field, we can annotate them using @Ignore.
@Ignore val picture: Bitmap?
  • We can use the indices property of @Entity annotation to add indices to an entity. Also, we can create unique indices by setting the unique property of an @Index annotation to true.
@Entity(indices = arrayOf(Index(value = ["last_name", "address"])))@Entity(indices = arrayOf(Index(value = ["first_name", "last_name"],
        unique = true)))

3. Data Access Object (DAO)

DAOs provide an API for accessing the database. This is an interface which is annotated with @Dao annotation. All the methods in this interface are used for getting data from the database or changing the database. These methods are annotated with annotations like @Query, @Insert, @Delete.

@Dao
interface UserDao {
  @Query("SELECT * FROM user")
  fun getAll(): List<User>
  
  @Query("SELECT * FROM user WHERE uid IN (:userIds)")
  fun loadAllByIds(userIds: IntArray): List<User>
  
  @Insert
  fun insertAll(vararg users: User)
  
  @Delete
  fun delete(user: User)
}

Here, all queries using UserDao are made on the caller thread. So we should take care that no method is invoked from the UI(main) thread.

Type Converters in Room

Sometimes, we might need to persist a custom data type in a single database column. We can use type converters for these types of use cases.

class Converters {
  @TypeConverter
  fun fromTimestamp(value: Long?): Date? {
  return value?.let { Date(it) }
  }

  @TypeConverter
  fun dateToTimestamp(date: Date?): Long? {
  return date?.time?.toLong()
  }
}

Next, we have to add the @TypeConverters annotation to the RoomDatabase class so that Room can use the converter, we’ve defined for each entity and DAO in that RoomDatabase.

@Database(entities = arrayOf(User::class), version = 1)
@TypeConverters(Converters::class)
abstract class UserDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao
}

So Room takes care of these concerns for us, we highly recommend using Room instead of SQLite.

That’s all about in this article.

Conclusion

In this article, we understood about Android Room Persistent Library Overview like Basic, advantages, How to use it, major components and custom type converters in Room.

Thanks for reading! I hope you enjoyed and learned about the basic of Android Room Persistent Library. 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 !!???

ReactJS – Recommended Valuable Design Principles You Need To Know

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about Recommended Design Principles used in ReactJS , and then we will also try to understand a better idea of how we decide what React does and what React doesn’t do, and what our development philosophy is like. The React recommends below common design principles which we will discuss one by one:

  • Composition
  • Common Abstraction
  • Escape Hatches
  • Stability
  • Interoperability
  • Scheduling
  • Developer Experience
  • Debugging
  • Configuration
  • Beyond the DOM
  • Implementation
  • Optimized for Tooling
  • Dogfooding

A famous quote about learning is :

Learning never exhausts the mind.

So, Let’s begin.

1. Composition

The key feature of React is composition of components. Components written by different people should work well together. It is important to us that you can add functionality to a component without causing rippling changes throughout the codebase.

For example, it should be possible to introduce some local state into a component without changing any of the components using it. Similarly, it should be possible to add some initialization and teardown code to any component when necessary.

Components are often described as “just functions” but in our view they need to be more than that to be useful. In React, components describe any composable behavior, and this includes rendering, lifecycle, and state. Some external libraries like Relay augment components with other responsibilities such as describing data dependencies. It is possible that those ideas might make it back into React too in some form.

2. Common Abstraction

In general, we resist adding features that can be implemented in userland. We don’t want to bloat your apps with useless library code. However, there are exceptions to this.

For example, if React didn’t provide support for local state or lifecycle methods, people would create custom abstractions for them. When there are multiple abstractions competing, React can’t enforce or take advantage of the properties of either of them. It has to work with the lowest common denominator.

This is why sometimes we add features to React itself. If we notice that many components implement a certain feature in incompatible or inefficient ways, we might prefer to bake it into React. We don’t do it lightly. When we do it, it’s because we are confident that raising the abstraction level benefits the whole ecosystem. State, lifecycle methods, cross-browser event normalization are good examples of this.

3. Escape Hatches

React is pragmatic. It is driven by the needs of the products written at Facebook. While it is influenced by some paradigms that are not yet fully mainstream such as functional programming, staying accessible to a wide range of developers with different skills and experience levels is an explicit goal of the project.

If we want to deprecate a pattern that we don’t like, it is our responsibility to consider all existing use cases for it and educate the community about the alternatives before we deprecate it. If some pattern that is useful for building apps is hard to express in a declarative way, we will provide an imperative API for it. If we can’t figure out a perfect API for something that we found necessary in many apps, we will provide a temporary subpar working API as long as it is possible to get rid of it later and it leaves the door open for future improvements.

4. Stability

We value API stability. At Facebook, we have more than 50 thousand components using React. Many other companies, including Twitter and Airbnb, are also heavy users of React. This is why we are usually reluctant to change public APIs or behavior.

However we think stability in the sense of “nothing changes” is overrated. It quickly turns into stagnation. Instead, we prefer the stability in the sense of “It is heavily used in production, and when something changes, there is a clear (and preferably automated) migration path.”

When we deprecate a pattern, we study its internal usage at Facebook and add deprecation warnings. They let us assess the impact of the change. Sometimes we back out if we see that it is too early, and we need to think more strategically about getting the codebases to the point where they are ready for this change.

If we are confident that the change is not too disruptive and the migration strategy is viable for all use cases, we release the deprecation warning to the open source community. We are closely in touch with many users of React outside of Facebook, and we monitor popular open source projects and guide them in fixing those deprecations.

Given the sheer size of the Facebook React codebase, successful internal migration is often a good indicator that other companies won’t have problems either. Nevertheless sometimes people point out additional use cases we haven’t thought of, and we add escape hatches for them or rethink our approach.

We don’t deprecate anything without a good reason. We recognize that sometimes deprecations warnings cause frustration but we add them because deprecations clean up the road for the improvements and new features that we and many people in the community consider valuable.

5. Interoperability

We place high value in interoperability with existing systems and gradual adoption. Facebook has a massive non-React codebase. Its website uses a mix of a server-side component system called XHP, internal UI libraries that came before React, and React itself. It is important to us that any product team can start using React for a small feature rather than rewrite their code to bet on it.

This is why React provides escape hatches to work with mutable models, and tries to work well together with other UI libraries. You can wrap an existing imperative UI into a declarative component, and vice versa. This is crucial for gradual adoption.

6. Scheduling

Even when your components are described as functions, when you use React you don’t call them directly. Every component returns a description of what needs to be rendered, and that description may include both user-written components like <LikeButton> and platform-specific components like <div>. It is up to React to “unroll” <LikeButton> at some point in the future and actually apply changes to the UI tree according to the render results of the components recursively.

This is a subtle distinction but a powerful one. Since you don’t call that component function but let React call it, it means React has the power to delay calling it if necessary. In its current implementation React walks the tree recursively and calls render functions of the whole updated tree during a single tick. However in the future it might start delaying some updates to avoid dropping frames.

This is a common theme in React design. Some popular libraries implement the “push” approach where computations are performed when the new data is available. React, however, sticks to the “pull” approach where computations can be delayed until necessary.

React is not a generic data processing library. It is a library for building user interfaces. We think that it is uniquely positioned in an app to know which computations are relevant right now and which are not.

If something is offscreen, we can delay any logic related to it. If data is arriving faster than the frame rate, we can coalesce and batch updates. We can prioritize work coming from user interactions (such as an animation caused by a button click) over less important background work (such as rendering new content just loaded from the network) to avoid dropping frames.

To be clear, we are not taking advantage of this right now. However the freedom to do something like this is why we prefer to have control over scheduling, and why setState() is asynchronous. Conceptually, we think of it as “scheduling an update”.

The control over scheduling would be harder for us to gain if we let the user directly compose views with a “push” based paradigm common in some variations of Functional Reactive Programming. We want to own the “glue” code.

It is a key goal for React that the amount of the user code that executes before yielding back into React is minimal. This ensures that React retains the capability to schedule and split work in chunks according to what it knows about the UI.

There is an internal joke in the team that React should have been called “Schedule” because React does not want to be fully “reactive”.

7. Developer Experience

Providing a good developer experience is important to us.

For example, we maintain React DevTools which let you inspect the React component tree in Chrome and Firefox. We have heard that it brings a big productivity boost both to the Facebook engineers and to the community.

We also try to go an extra mile to provide helpful developer warnings. For example, React warns you in development if you nest tags in a way that the browser doesn’t understand, or if you make a common typo in the API. Developer warnings and the related checks are the main reason why the development version of React is slower than the production version.

The usage patterns that we see internally at Facebook help us understand what the common mistakes are, and how to prevent them early. When we add new features, we try to anticipate the common mistakes and warn about them.

We are always looking out for ways to improve the developer experience. We love to hear your suggestions and accept your contributions to make it even better.

8. Debugging

When something goes wrong, it is important that you have breadcrumbs to trace the mistake to its source in the codebase. In React, props and state are those breadcrumbs.

If you see something wrong on the screen, you can open React DevTools, find the component responsible for rendering, and then see if the props and state are correct. If they are, you know that the problem is in the component’s render() function, or some function that is called by render(). The problem is isolated.

If the state is wrong, you know that the problem is caused by one of the setState() calls in this file. This, too, is relatively simple to locate and fix because usually there are only a few setState() calls in a single file.

If the props are wrong, you can traverse the tree up in the inspector, looking for the component that first “poisoned the well” by passing bad props down.

This ability to trace any UI to the data that produced it in the form of current props and state is very important to React. It is an explicit design goal that state is not “trapped” in closures and combinators, and is available to React directly.

While the UI is dynamic, we believe that synchronous render() functions of props and state turn debugging from guesswork into a boring but finite procedure. We would like to preserve this constraint in React even though it makes some use cases, like complex animations, harder.

9. Configuration

We find global runtime configuration options to be problematic.

For example, it is occasionally requested that we implement a function like React.configure(options) or React.register(component). However this poses multiple problems, and we are not aware of good solutions to them.

What if somebody calls such a function from a third-party component library? What if one React app embeds another React app, and their desired configurations are incompatible? How can a third-party component specify that it requires a particular configuration? We think that global configuration doesn’t work well with composition. Since composition is central to React, we don’t provide global configuration in code.

We do, however, provide some global configuration on the build level. For example, we provide separate development and production builds. We may also add a profiling build in the future, and we are open to considering other build flags.

10. Beyond the DOM

We see the value of React in the way it allows us to write components that have fewer bugs and compose together well. DOM is the original rendering target for React but React Native is just as important both to Facebook and the community.

Being renderer-agnostic is an important design constraint of React. It adds some overhead in the internal representations. On the other hand, any improvements to the core translate across platforms.

Having a single programming model lets us form engineering teams around products instead of platforms. So far the tradeoff has been worth it for us.

11. Implementation

We try to provide elegant APIs where possible. We are much less concerned with the implementation being elegant. The real world is far from perfect, and to a reasonable extent we prefer to put the ugly code into the library if it means the user does not have to write it. When we evaluate new code, we are looking for an implementation that is correct, performant and affords a good developer experience. Elegance is secondary.

We prefer boring code to clever code. Code is disposable and often changes. So it is important that it doesn’t introduce new internal abstractions unless absolutely necessary. Verbose code that is easy to move around, change and remove is preferred to elegant code that is prematurely abstracted and hard to change.

12. Optimized for Tooling

Some commonly used APIs have verbose names. For example, we use componentDidMount() instead of didMount() or onMount(). This is intentional. The goal is to make the points of interaction with the library highly visible.

In a massive codebase like Facebook, being able to search for uses of specific APIs is very important. We value distinct verbose names, and especially for the features that should be used sparingly. For example, dangerouslySetInnerHTML is hard to miss in a code review.

Optimizing for search is also important because of our reliance on codemods to make breaking changes. We want it to be easy and safe to apply vast automated changes across the codebase, and unique verbose names help us achieve this. Similarly, distinctive names make it easy to write custom lint rules about using React without worrying about potential false positives.

JSX plays a similar role. While it is not required with React, we use it extensively at Facebook both for aesthetic and pragmatic reasons.

In our codebase, JSX provides an unambiguous hint to the tools that they are dealing with a React element tree. This makes it possible to add build-time optimizations such as hoisting constant elements, safely lint and codemod internal component usage, and include JSX source location into the warnings.

13. Dogfooding

 Dogfooding it means that our vision stays sharp and we have a focused direction going forward.

We try our best to address the problems raised by the community. However we are likely to prioritize the issues that people are also experiencing internally at Facebook. Perhaps counter-intuitively, we think this is the main reason why the community can bet on React.

Heavy internal usage gives us the confidence that React won’t disappear tomorrow. React was created at Facebook to solve its problems. It brings tangible business value to the company and is used in many of its products. 

For example, we added support for web components and SVG to React even though we don’t rely on either of them internally. We are actively listening to your pain points and address them to the best of our ability. The community is what makes React special to us, and we are honored to contribute back.

After releasing many open source projects at Facebook, we have learned that trying to make everyone happy at the same time produced projects with poor focus that didn’t grow well. Instead, we found that picking a small audience and focusing on making them happy brings a positive net effect. That’s exactly what we did with React, and so far solving the problems encountered by Facebook product teams has translated well to the open source community.

The downside of this approach is that sometimes we fail to give enough focus to the things that Facebook teams don’t have to deal with, such as the “getting started” experience. We are acutely aware of this, and we are thinking of how to improve in a way that would benefit everyone in the community without making the same mistakes we did with open source projects before.

That’s all about in this article.

Conclusion

In this article, We understood about Recommended Design Principles used in ReactJS.

Thanks for reading ! I hope you enjoyed and learned about React recommended design principles. 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 and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

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 !!???

ReactJS – Is SOLID Valid For React?

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about topic ” Is Solid principle valid for React? “. We will focus each principle details of the SOLID one by one using below points:

  • What does the principle mean?
  • How does React adhere to it ?


SOLID is an interesting topic in React. While React doesn’t force the principles onto you, at least it often allows you to follow them.

A famous quote about learning is :

That is what learning is. You suddenly understand something you’ve understood all your life, but in a new way. ”  

So, Let’s begin.


What does SOLID stand for?

SOLID is an acronym build by the first letter of 5 object oriented programming design principles. The basic idea is, if you follow these principles, your software gets better.

  • Single responsibility principle
  • Open/closed principle
  • Liskov substitution principle
  • Interface segregation principle
  • Dependency inversion principle


What do these principles imply and how does React adhere to it?


1. Single Responsibility Principle

What does it mean?

A class should only have a single responsibility.

How does React adhere to it?

React applications consist of components, which are classes that inherit from the React.Component class. You can start building your application as a component and if it gets too complex, you can split this component up into multiple smaller components.

React doesn’t force you to adhere to the principle, but you can split up your component classes into smaller components till you achieved single responsibility for all of your components.

For example, you could have a button component that just handles clicks and an input component that just handles user input. A level above you use a form component that uses multiple instances of the button and input component to get user credentials and above that a connection component that takes form data and sends it to a server.


2. Open Close Principle

What does it mean?

Software entities should be open for extension, but closed for modification. Which means you can extends it without modifying its source code.

How does React adhere to it?

Reacts component model is build around aggregation instead of inheritance. So you only extend the base React.Component and not its children. This prevents you from overriding behavior of existing components directly. The only way is to wrap it with your own component.

You could for example wrap a Button with a RedButton that always applies specific styles to the basic Button, but the Button is closed for modification.

This is less flexible than inheritance, but it also simplifies the API. While you don’t have direct access to the methods like in an extension, you only have to care about props in your aggregation.


3. Liskov Substitution Principle

What does it mean?

Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.

How does React adhere to it?

Well, it doesn’t use inheritance at all. Sure you extend React.Component, but this class is essentially treated as abstract in React applications, you never directly create an object from it, so you never have to replace it with a child-class later.

On the other hand, you find yourself writing aggregations that should act like their wrapped components rather often. Like the Button I mentioned before. You want that RedButton to be already styled, but you also want it to act like the Button, but since the API between components always is just props, it’s often simple to add something while your wrappers props are passed down to the wrapped component. Because everything is dynamic, your wrapper doesn’t even have to know everything about the data that would originally be passed down to the wrapped component, in the RedButton example it would just have to know about the style.


4. Interface Segregation Principle

What does it mean?

Many client-specific interfaces are better than one general-purpose interface.

How does React adhere to it?

Because React is written in JavaScript, it benefits from the dynamic nature of this language. There are no formal interfaces. If you don’t use refs, which allow you to directly call class methods of a component, the only interaction between components is via props and nobody forces you to use props you don’t need.

If you have a wrapper component that passes down an onClick handler that shows an alert with the wrapped components class name, you can use this wrapper to wrap all components that use this onClick prop and if they don’t, the handler is just ignored.

My experience with this fact was that it simplified many things, you wouldn’t get lost in defining many small interfaces beforehand. The drawback was that I often found me in situations where I passed down props the wrapped component did simply ignore silently. At least glamorous-native threw a few warnings when I tried to pass down unknown CSS attributes. For this it often helps to use PropTypes or something.


5. Dependency Inversion Principle

What does it mean?

One should depend upon abstractions, not concretions.

How does React adhere to it?

In practice, this principle is often followed by removing class names from other classes. Like, you could have a List that has Items, so you could get the idea to create your Item objects inside the List class, now you have your List tightly coupled with your Item. Somewhere in your List class is a new Item(...) or Item.create(...) etc.

React doesn’t strictly adhere to it, you can pass an array of string to your List component and create Item children from it no problem.

But you can also tell the List it should simply render out its children independent of what they are, maybe add some keys to it or justify them etc.

Now you can create an array of Items, sprinkle it with some HighlightItems, both created from different string arrays and put them inside your List who won’t be the wiser.

That’s all about in this article.


Conclusion

In this article, We understood What do SOLID principles imply and how does React adhere to it. We learnt that React doesn’t force the principles onto you, but at least it often allows you to follow them. Sometimes it gets easier because of JavaScript, sometimes JavaScript makes it harder, but overall it is possible to write SOLID applications with React..

Thanks for reading ! I hope you enjoyed and learned about SOLID imply and adhere concepts in React. 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 and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

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 !!???

Android – How Does RecyclerView Work Internally?

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about how recyclerView actually works in the Android system. This article will focus the below points to understand the Android RecyclerView Working Concepts:

  • Overview
  • What is RecyclerView?
  • The Building Components of RecyclerView
  • The Benefits of RecyclerView
  • RecyclerView Used Patterns
  • How it actually works?
  • The View Optimization of RecyclerView

A famous quote about learning is :

Tell me and I forget, teach me and I may remember, involve me and I learn.

So Let’s begin one by one.

Overview

Displaying a list or grid of data is one of the most common UI tasks in Android. Lists vary from simple to very complex. A list of text views might show simple data, such as a shopping list. A complex list, such as an annotated list of vacation destinations, might show the user many details inside a scrolling grid with headers.

To support all these use cases, Android provides the RecyclerView widget. So what’s next.

What is RecyclerView?

RecyclerView is a ViewGroup, which populates a list on a collection of data provided with the help of ViewHolder and draws it to the user on-screen.

The Building Components of RecyclerView

The major components of RecyclerView are:

  • Adapter
  • ViewHolder
  • LayoutManager

1. Adapter

It is a subtype of RecyclerView. Adapter class. This takes the data set which has to be displayed to the user in RecyclerView. It is like the main responsible class to bind the views and display it.

Most of the tasks happen inside the adapter class of the recyclerView.

2. ViewHolder

ViewHolder is a type of a helper class that helps us to draw the UI for individual items that we want to draw on the screen.

All the binding of Views of the individual items happens in this class. It is a subclass of RecyclerView.ViewHolder class.

3. LayoutManager

LayoutManager in recyclerView helps us to figure out how we need to display the items on the screen. It can be linearly or in a grid. RecyclerView provides by default a few implementations of layoutManager out of the box.

It is like the governing body of recyclerView which tells the recyclerView’s adapter when to create a new view.

The Benefits of RecyclerView

The greatest benefit of RecyclerView is that it is very efficient for large lists:

  • By default, RecyclerView only does work to process or draw items that are currently visible on the screen. For example, if our list has a thousand elements but only 10 elements are visible, RecyclerView does only enough work to draw 10 items on the screen. When the user scrolls, RecyclerView figures out what new items should be on the screen and does just enough work to display those items.
  • When an item scrolls off the screen, the item’s views are recycled. That means the item is filled with new content that scrolls onto the screen. This RecyclerView behavior saves a lot of processing time and helps lists scroll fluidly.
  • When an item changes, instead of redrawing the entire list, RecyclerView can update that one item. This is a huge efficiency gain when displaying lists of complex items!

In the sequence shown below, we can see that one view has been filled with data, ABC. After that view scrolls off the screen, RecyclerView reuses the view for new data, XYZ.

RecyclerView Used Patterns

RecyclerView uses Adapter pattern to display complex lists in the UI Screen after transform app data.

If we ever travel between countries that use different electric sockets, we probably know how we can plug your devices into outlets by using an adapter. The adapter lets you convert one type of plug to another, which is really converting one interface into another.

The adapter pattern in software engineering helps an object to work with another API. RecyclerView uses an adapter to transform app data into something the RecyclerView can display, without changing how the app stores and processes the data.

For the sleep-tracker app, we build an adapter that adapts data from the Room database into something that RecyclerView knows how to display, without changing the ViewModel.

How it actually works?

So, now we are going to discuss how the recyclerView actually works. When we talk about recyclerView, you would always hear someone saying that it recycles the views. But what does it actually mean?

So, let’s say when we are scrolling the list which has 50 items in the collection and we show only 5 items at once in the list.

Here, item 1 to item 5 is the ones that are visible on the screen. item x is the one that will be loaded next on the screen when we scroll up. All the items here have their own instance of ViewHolder and the ViewHolder here is helpful for caching the specific item’s view.

This is how recycling of views happens in recyclerView which is one of the main reasons for the better improvement of recyclerView. In this process, the views of the item are reused to draw new items on the screen.

Similarly, if we have multiple view types, let’s say ViewType1 and ViewType2 then we would have two different collections of scrapped view of type ViewType1 and ViewType2.

And while recycling the views, the ViewType1 view will be allocated to only views of ViewType1 and ViewType2 views will be allocated to ViewType2 views.

This is how recyclerView works internally and efficiently.

The View Optimization of RecyclerView

RecyclerView optimizes the view using ViewHolders.

So, let us say we have 100 items be displayed on the list, and we want to show 5 items on the screen.

Each item here has 1 TextView and 1 ImageView in the item.

So, to map each view using findViewById is always an expensive task and just imagine the number of findViewByIds we might need to map all the TextViews and ImageViews of 100 items i.e 200 findViewByIds.

So, when we are using RecyclerView, then only 6 items are created initially with 5 loaded at once to be displayed on-screen and one is the one to be loaded.

Now, if we scroll the list then we have 7 viewHolders. One each for scrapped view and to be loaded view and 5 for the ones which are displayed.

So, at a time, maximum findViewByIds that we are using are only 14 as we have a maximum of 7 ViewHolders.

Because of ViewHolders and recycling of views, we have got the performance improvement in RecyclerViews.

That’s all about in this article.

Conclusion

In this article, We understood how recyclerView actually works in the Android system. This article demonstrates RecyclerView Concepts, Building Blocks , Benefits, Used Patterns, Internal working process and the reasons behind view optimization and performance improvement in RecyclerView.

Thanks for reading ! I hope you enjoyed and learned about Android RecyclerView Concepts. 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 and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

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 !!???

Android – How To Secure API Keys Using Android NDK ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about how to secure API Keys using the Android Native Development Kit. We will focus the below points to understand the API Keys Security Concepts in Android NDK:

  • What is the current problem during secure API Keys?
  • What is the proposed solution to secure the API Keys?
  • How to do this in Android?

A famous quote about learning is :

The more that you read, the more things you will know. The more that you learn, the more places you’ll go.

So Let’s begin one by one.

Overview

What is the current problem during secure API Keys?

Here First question, What is the current problem during secure API Keys?

The Answer is :

While developing Android applications, we use various third-parties libraries that make the development of our application fast. In these libraries, we just call some functions according to our need and we don’t know the code of these functions and we don’t care about that. But to call these functions, we need API keys that are different for different users. Some of these libraries are paid and if somehow, someone gets our API key then we might land to high payment bills and many other problems. During the starting days to Android development, we put our API keys either in strings.xml file or in gradle file.

strings.xml file

Following is an example of storing an API key in strings.xml file:

<resources>
    <string name="app_name">SecureAPI</string>
    <string name="MyAPIKey">YOUR_API_KEY_HERE</string>
</resources>

The problem with approach is that anyone can get the API key by reverse engineering.

gradle file

Another approach that was used is the gradle file approach. Here we add the API key in the gradle.properties file:

#gradle.properties file

#API Key
APIKey = "YOUR_API_KEY_HERE"

After that, import the API key as buildConfigField in the build.gradle file.

buildTypes {
    debug {
        buildConfigField 'String', "ApiKey", MyAPIKey
        resValue 'string', "api_key", MyAPIKey
    }
    ...
}

But still anyone can get the API key by reverse engineering your code. So, both methods failed to secure the API keys. We need a certain concrete method that can be used so that even after reverse-engineering the code, no one can get the desired API key. 

Cool !! So We understood the problem of secure API keys in Android development.

What is the proposed solution to secure the API Keys ?

So the next question is, What is the proposed solution to secure the API Keys ? And what should we do so that even after reverse engineering no one can get the API key ?

The Answer is :

One solution to the above problem can be the use of native language in our application code. In the native languages like in C or C++, the Android Native Development Kit(NDK) compiles the code to .so file. The benefit with this .so file is that it contains binary numbers i.e. in the form of 0s and 1s. So, even after reverse engineering, we will get 0s and 1s and it is very difficult to identify what is written in the form of 0s and 1s.

Great !!

There are methods to get the code from 0s and 1s also, but as I said earlier, we are just providing some extra security layers to our code.

How to do this in Android ?

So next, we will discuss that How to do this in Android ?

The Answer is :

In Android, we have the support of Native languages with the help of the Android Native Development Kit (NDK). Also, there is JNI (Java Native Interface) in Android. JNI defines a way for the byte code that is generated from the Java or Kotlin code to interact with the native code i.e. code written in C or C++.

Three Approaches to secure our API keys

So, with the help of Android NDK, we can secure the API keys. Based on the versions of Android Studio, we have three approaches to secure our API keys using :

  • The Native C++ template
  • CMake
  • ndk-build

But before moving on to these approaches, there are some prerequisites. So, before moving onto that, we have to download some tools. Follow the below steps:

  1. In Android Studio, click on Tools > SDK Manager > SDK Tools.
  2. Select LLBDNDK, and CMake.
  3. Click on Apply and after downloading and installing click on OK.

  • LLBD: It is used by Android Studio to debug the native code present in the project.
  • NDK: Native Development Kit(NDK) is used to code in C and C++ i.e. native languages for Android.
  • CMake: It is an open-source system that manages the build process in an operating system and a compiler-independent manner.

Now, we have done with downloading the tools, let’s quickly move on to the approaches of securing the API keys.

1. The Native C++ template

In the latest versions of Android Studio, we have support for native code i.e. for the C and C++. 

We can find that by default we will be having native-lib.cpp file and the CMakeLists.txt file added to our project under the cpp directory. The native-lib.cpp file is the file that contains our API keys. We can add our API keys in the file as below:

#include <jni.h>
#include <string>

extern "C" JNIEXPORT jstring JNICALL
Java_com_coolmonktechie_myapplication_APIKeyLibrary_getAPIKey(JNIEnv* env, jobject /* this */) {
    std::string api_key = "YOUR_API_KEY_GOES_HERE";
    return env->NewStringUTF(api_key.c_str());
}

Following is the description of the above code:

  • Here, we have to follow the combination of PackageName_ActivityName_MethodName.
  • In the above example, com_coolmonktechie_myapplication is the package name, APIKeyLibrary is the file name and getAPIKey is the method that is used to get the API keys from the native code.
  • We can directly return the API key but normally people use some encryption technique to encrypt the API key. So, the NewStringUTF() method is used to do the UTF-8 encoding.

Now, to use our API key in the Activity or in any file, go to the Activity or the file where we want to use our API keys. To load the native code that we have written, we need to call the System.loadLibrary(“native-lib”) method in the init block.

init {
        System.loadLibrary("native-lib")
}

Now, declare a Kotlin external function with the same name as used in the native code.

external fun getAPIKey(): String

Finally, we can get the API key by calling:

APIKeyLibrary.getAPIKey()

That’s all! We have secured our API key.

2. CMake

Apart from using the Native C++ template, we can use the CMake to secure the API keys.

CMake is used to control the software compilation process using simple platform and compiler independent configuration files, and generate native makefiles and workspaces that can be used in the compiler environment of our choice.

After installing the required tools, Under the app/src/main directory, create a directory named cpp. In the cpp directory, create a native file where we want to store our API keys. So, create a file named api-keys.cpp and add the below code:

#include <jni.h>
#include <string>

extern "C" JNIEXPORT jstring JNICALL
Java_com_coolmonktechie_myapplication_APIKeyLibrary_getAPIKey(JNIEnv* env, jobject /* this */) {
    std::string api_key = "YOUR_API_KEY_GOES_HERE";
    return env->NewStringUTF(api_key.c_str());
}

In the app/ directory, we need to add one text file named CMakeLists.txt file. It is a CMake build script. Add the below content into it:

# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html

# Sets the minimum version of CMake required to build the native library.

cmake_minimum_required(VERSION 3.4.1)

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# We can define multiple libraries, and CMake builds them for us.
# Gradle automatically packages shared libraries with our APK.

add_library( # Sets the name of the library.
api-keys

# Sets the library as a shared library.
        SHARED

# Provides a relative path to our source file(s).
src/main/cpp/api-keys.cpp )

# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, we only need to specify the name of the public NDK library
# we want to add. CMake verifies that the library exists before
# completing its build.

find_library( # Sets the name of the path variable.
log-lib

# Specifies the name of the NDK library that
# we want CMake to locate.
        log )

# Specifies libraries CMake should link to our target library. We
# can link multiple libraries, such as libraries we define in this
# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries( # Specifies the target library.
native-lib

# Links the target library to the log library
# included in the NDK.
        ${log-lib} )

Now, We have to specify the path of our CMakeLists file in the build.gradle file. So, add the below code in build.gradle file:

android {
    ...
    defaultConfig {
        ...
    }
    buildTypes {
        ...
    }
    externalNativeBuild {
        cmake {
            path 'CMakeLists.txt'
        }
    }
}

Now, to access the API keys from our Activity or file.

3. ndk-build

To compile the native code present in the project, Android Studio supports the ndk-build. Here, we will be having an Android.mk build file that is used by ndk-build.

The Android.mk file is present inside the jni/ directory. It describes our sources and shared libraries to the build system. The basic purpose of the Android.mk file is to define project-wide settings that are not defined by the build system or by Application.mk or by environment variables. Also, the syntax of the Android.mk file allows us to group our sources into modules.

To use ndk-build, Under the app/src/main directory, create a directory named jni. Here we will be having our .mk files and the native code file. In the jni directory that we have created in the previous step, add one file named Android.mk and add the below lines of code to it:

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := api-keys
LOCAL_SRC_FILES := api-keys.c

include $(BUILD_SHARED_LIBRARY)

Following is the description of the above code:

  • The LOCAL_PATH variable indicates the location of the source file. my-dir is a macro function provided by the build system to return the current directory.
  • The CLEAR_VARS is used to clear many LOCAL_XXX variables for us like LOCAL_MODULE, LOCAL_SRC_FILES, etc. It doesn’t clear LOCAL_PATH.
  • The LOCAL_MODULE variable stores the name of the module that we want to build. The module name must be unique and we shouldn’t use any space in the module name.
  • The LOCAL_SRC_FILES variable contains a list of C or C++ files that are present in the module.
  • The BUILD_SHARED_LIBRARY variable is used to tie everything together. It determines what to build, and how to do it. It collects the information that we defined in LOCAL_XXX variables since the most recent include.

In the jni directory, create another file named Application.mk file and add the below code:

APP_ABI := all

The Application.mk file is used to specify the project-wide settings for the ndk-build.

The variable APP_ABI is used to specify the ABIs whose code should be generated by the build system. By default, the build system generates the code for all non-deprecated ABIs.

The last file to be added in the jni directory is our native code file. So, in the jni directory, add one file named api-keys.c and add the below code into it:

#include <jni.h>

//For first API key
JNIEXPORT jstring JNICALL
Java_com_coolmonktechie_myapplication_APIKeyLibrary_getAPIKey(JNIEnv *env, jobject instance) {

    return (*env)->  NewStringUTF(env, "YOUR_API_GOES_HERE");

}

After adding the required files in your jni directory, our next aim is to provide the path of our Android.mk file in the build.gradle file.

android {
    ...
    defaultConfig {
        ...
    }
    buildTypes {
        ...
    }
    externalNativeBuild {
        ndkBuild {
            path 'src/main/jni/Android.mk'
        }
    }
}

Now, to access the API keys from your Activity or file.

That’s all about in this article.

Conclusion

In this article, We understood how to secure our API keys with the help of the Android Native Development Kit. We saw three methods of doing so i.e. the ndk-build method, the CMake method and the easiest one i.e. using the native c++ template in our Application project..

Thanks for reading ! I hope you enjoyed and learned about Android Secure API Keys Concepts and Methods. 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 and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

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 !!???

ReactJS – A Overview of class components and functional components with Hooks

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about class components and functional components differences and which one is best use for Hooks. A famous quote about learning is :

The beautiful thing about learning is that nobody can take it away from you.”

So Let’s begin.

The simplest way to define a component in React is to write a JavaScript function that returns a React element:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

The Welcome component accepts props which is an object that contains data and returns a React element. We can then import and render this component in another component.

The class component uses a programming methodology called Encapsulation which basically means that everything relevant to the class component will live within it. Life-cycle methods (constructorscomponentDidMount()render, and so on) give components a predictable structure.

Encapsulation is one of the fundamentals of OOP (Object-Oriented Programming). It refers to the bundling of data within the methods that operate on that data, and is used to hide the values or state of a structured data object inside a class — preventing unauthorized parties’ direct access to them.

With Hooks, the composition of a component changes from being a combination of life-cycle Hooks — to functionalities with some render at the end.

Function Component

The example below shows how custom Hooks can be used in a functional component (without showcasing what the body is). However, what it does or can do is not limited. It could be instantiating state variables, consuming contexts, subscribing the component to various side effects — or all of the above if you’re using a custom hook!

function {
  useHook{...};
  useHook{...};
  useHook{...};
  return (
    ...
  );
}

Class Component

class component requires you to extend from React.Component and create a render function which returns a React element. This requires more code but will also give you some benefits.

class {
  constructor(props) {...}
  componentDidMount() {...}
  componentWillUnmount() {...}
  render() {...}
}

So, Which one is best for Hooks ?

The Answer is :

There are some benefits you get by using functional components in React:

  1. It will get easier to separate container and presentational components because you need to think more about your component’s state if you don’t have access to setState() in your component.
  2. Functional components are much easier to read and test because they are plain JavaScript functions without state or lifecycle-hooks.
  3. You end up with less code.
  4. The React team mentioned that there may be a performance boost for functional components in future React versions.

This leads to the first best practice when using React Hooks.

That’s all about in this article.

Conclusion

In this article, We understood the Class component and functional component differences and benefits in Hooks with Which one is best for Hooks.

Thanks for reading ! I hope you enjoyed and learned about React class components and functional components differences and which one is best use for Hooks. 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 and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

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 !!???

ReactJS – Fundamental Best Practice And Tips

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about fundamental Best Practice and Tips in React Application. For any application development, fundamental best practice and tips are most important for developer who developed the application. We will discuss the below most fundamental of React best Practices one by one:

  1. Keep components small and function-specific
  2. Reusability
  3. Consolidate duplicate code – DRY your code
  4. Put CSS in JavaScript
  5. Comment only where necessary
  6. Name the component after the function
  7. Use capitals for component names
  8. Mind the other naming conventions
  9. Separate stateful aspects from rendering
  10. Code should execute as expected and be testable
  11. All files related to any one component should be in a single folder
  12. Use tools like Bit
  13. Use snippet libraries
  14. Write tests for all code
  15. Use ES Lint for better coding conventions.

A famous quote about learning is :

An investment in knowledge pays the best interest.”

So Let’s begin.

1. Keep components small and function-specific

As we all know, with React, it’s possible to have huge components that execute a number of tasks. But a better way to design components is to keep them small, so that one component corresponds to one function. Ideally, a single component should render a specific bit of your page or modify a particular behavior.

There are many advantages to this:

  • Function-specific components can be standalone, which makes testing and maintenance easier.
  • Each small component can be reused across multiple projects.
  • Components executing general functions can be made available to the community.
  • With smaller components, it’s easier to implement performance optimizations.
  • It’s easier to update smaller components.
  • Bigger components have to perform harder and may be difficult to maintain.

The balance between creating one concise component and creating multiple function-specific components can vary from organization to organization. After all, you can have as many components as you want, and recombine them in any way you want to achieve the same end result.

2. Reusability 

By sticking to the rule of one function = one component, you can improve the reusability of components. What this means is that you should skip trying to build a new component for a function if there already exists a component for that function.

Reusability is important, so keep creation of new components to the minimum required.

For example, you can even go further and create a Button component that can handle icons. Then, each time you need a button, you’ll have a component to use. Making it more modular will allow you to cover many cases with the same piece of code. You have to aim somewhere in the middle. Your components should be abstract enough, but shouldn’t be overly complex.

class IconButton extends React.Component {
  [...]
  render() {
    return (
      <button onClick={this.props.onClick()}>
        <i class={this.props.iconClass}></i>
      </button>
    );
  }
}

3. Consolidate duplicate code – DRY your code

A common rule for all code is to keep it as brief and concise as possible.

Here, React best practices also instruct you to keep code brief and precise. One way to do this is to avoid duplication – Don’t Repeat Yourself (DRY).

You can achieve this by scrutinizing the code for patterns and similarities. This relies heavily on the reusability principle in React. Let’s say you want to add multiple buttons that contain icons, instead of adding the markup for each button, you can simply use the IconButton component that we shown above. You could even go further by mapping everything into an array.

const buttons = ['facebook', 'twitter', 'youtube'];

return (
  <div>
    {
      buttons.map( (button) => {
        return (
          <IconButton
            onClick={doStuff( button )}
            iconClass={button}
          />
        );
      } )
    }
  </div>
);

4. Put CSS in JavaScript

When you start working on a project, it is a common practice to keep all the CSS styles in a single SCSS file. The use of a global prefix prevents any potential name collisions. However, when your project scales up, this solution may not be feasible.

There are many libraries that enable you to write CSS in JS. EmotionJS and Glamorous are the two most popular CSS in JS libraries.

5. Comment only where necessary

Attach comments to code only where necessary. This is not only in keeping with React best practices, it also serves two purposes at the same time:

  • It’ll keep code visually clutter free.
  • You’ll avoid a potential conflict between comment and code, if you happen to alter the code at some later point in time.

6. Name the component after the function

It’s a good idea to name a component after the function that it executes so that it’s easily recognizable.

For example, ProductTable – it conveys instantly what the component does. On the other hand, if you name the component based on the need for the code, it can confuse you at a future point of time.

One more example, it’s preferable to name a component Avatar so that it can be used anywhere – for authors, users or in comments. Instead, if we name the component AuthorAvatar in the context of its usage, we’d be limiting the utility of that component.

Besides, naming a component after the function makes it more useful to the community as it’s more likely to be discovered.

7. Use capitals for component names

If you’re using JSX (a JavaScript extension), the names of the components you create need to begin with uppercase letters. For instance, you’ll name components as SelectButton instead of selectbutton, or Menu instead of menu. We do this so that JSX can identify them differently from default HTML tags.

8. Mind the other naming conventions

When working with React, you are generally using JSX (JavaScript Extension) files. Any component that you create for React should therefore be named in upper camel case. This translates to names without spaces and the capitalizing the first letter of every word.

If you want to create a function that submits a form, you should name it SubmitForm in upper camel case, rather than submitFormsubmit_form, or submit_form. Camel case is also called Pascal case.

PascalCase is a naming convention in which the first letter of each word in a compound word is capitalized. Software developers often use PascalCase when writing source code to name functions, classes, and other objects.

PascalCase is similar to camelCase, except the first letter in PascalCase is always capitalized. Below are some examples.

  • PascalCase: NewObject;
  • camelCase: newObject;
  • PascalCase: LongFunctionName()
  • camelCase: longFunctionName()

Both PascalCase and CamelCase help developers distinguish words within names. For example, “LongFunctionName” is more readable than “longfunctionname.”

9. Separate stateful aspects from rendering

Components in React can be stateful or stateless.

Stateful components store information about the component’s state and provide the necessary context. In contrast, stateless components have no memory and cannot give context to other parts of the UI. They only receive props (inputs) from parent component and return you JSX elements. They are scalable and reusable, and similar to pure function in JavaScript.

One of React best practices is to keep your stateful data-loading logic separate from your rendering stateless logic. It’s better to have one stateful component to load data and another stateless component to display that data. This reduces the complexity of the components.

The later React versions v16.8 have a new feature – React Hooks, which write stateful function-related components. This may eventually eliminate the need for class-based components.

For example, your app is fetching some data on mount. What you want to do is manage the data in the main component and pass the complex render task to a sub-component as props.

import RenderTable from './RenderTable';

class Table extends Component {
  state = { loading: true };

  render() {
    const { loading, tableData } = this.state;
    return loading ? <Loading/> : <RenderTable data={tableData}/>;
  }

  componentDidMount() {
    fetchTableData().then( tableData => {
      this.setState( { loading: false, tableData } );
    } );
  }
}

10. Code should execute as expected and be testable

The code you write should behave as expected, and be testable easily and quickly. It’s a good practice to name your test files identical to the source files with a .test suffix. It’ll then be easy to find the test files.

In React to test component we use Jest and Enzyme. Jest was created by Facebook and is a testing framework to test javascript and React code. Together with Airbnb’s Enzyme, which is a testing utility, makes it the perfect match to easily test your React application.

11. All files related to any one component should be in a single folder

Keep all files relating to any one component in a single folder, including styling files.

If there’s any small component used by a particular component only, it makes sense to keep these smaller components all together within that component folder. The hierarchy will then be easy to understand – large components have their own folder and all their smaller parts are split into sub-folders. This way, you can easily extract code to any other project or even modify the code whenever you want.

For instance, for the Form component, all pieces such as CSS files, icons, images, tests and any other sub-components relating to Form should all reside in the same folder. If you name files sensibly, and keep related files together logically, you’ll not have any difficulty finding them later.

12. Use tools like Bit

One of React best practices that helps to organize all your React components is the use of tools like Bit.

These tools help to maintain and reuse code. Beyond that, it helps code to become discoverable, and promotes team collaboration in building components. Also, code can be synced across projects.

13. Use snippet libraries

Code snippets help you to keep up with the best and most recent syntax. They also help to keep your code relatively bug free, so this is one of the React best practices that you should not miss out on.

There are many snippet libraries that you can use, like, ES7 React, Redux, JS Snippets, etc.

14. Write tests for all code

In any programming language, adequate testing ensures that any new code added to your project integrates well with existing code and does not break existing functionality. It is a good idea to write tests for any new component that you create. As a good practice, you should create a __Test__ directory within your component’s directory to house all relevant tests.

You can broadly divide tests in React into two parts: testing the functionality of components using a React app, and tests on your complete application once it renders in the browser. You can use cross browser testing tools for tests in the latter category.

For the former, you can use a JavaScript test runner, Jest to emulate the HTML DOM using jsdom to test React components. While a completely accurate test is only possible in a browser on a real device, Jest provides a good approximation of the real testing environment during the development phase of your project.

15. Use ES Lint for better coding conventions

Linting is a process wherein we run a program that analyses code for potential errors.

Well run projects have clear consistent coding conventions, with automated enforcement. Besides checking style, linters are also excellent tools for finding certain classes of bugs, such as those related to variable scope. Assignment to undeclared variables and use of undefined variables are examples of errors that are detectable at lint time.

That’s all about React fundamental best practices and tips.

Conclusion

In this article, We understood the list of React fundamental best practices is going to help you put your projects on the right track, and avoid any potential problems later down the road.

Thanks for reading ! I hope you enjoyed and learned about React fundamental best practices list. 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 and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

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 !!???

Android – An Overview of Android JetPack

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about Android Jetpack and Jetpack related components. We will discuss about the below Android Jetpack related topics :

  • What is Android Jetpack and why should we use it ?
  • What is Android Jetpack Components ?

A famous quote about learning is :

” That is what learning is. You suddenly understand something you’ve understood all your life, but in a new way.”

So Let’s begin.

In the above diagram, It represents a set of components, tools and guidance to make great Android apps. 

Cool !!

So first, we understand the Android Jetpack.

What is Android Jetpack ?

“Jetpack is a suite of libraries, tools, and guidance to help developers write high-quality apps more easily. These components help you follow best practices, free you from writing boilerplate code, and simplify complex tasks, so you can focus on the code you care about.”

Jetpack comprises the androidx.* package libraries, unbundled from the platform APIs. This means that it offers backward compatibility and is updated more frequently than the Android platform, making sure you always have access to the latest and greatest versions of the Jetpack components.

Android Jetpack is a collection of Android software components which helps us in building great Android apps.These software components help in:

  • Following the best practices and writing the boilerplate code.
  • Making complex things very simple.

Prior to Android Jetpack, we had many challenges during developing the android application:

  • Managing activity lifecycles in the application.
  • Surviving configuration changes.
  • Preventing memory leaks.

All these major problems have been solved by the Android Jetpack’s software components.

So, the solution for all the problems is Android Jetpack.

Another most important thing about the Jetpack is that it gets updated more frequently than the Android platform so that we always get the latest version.

Next question, We talk about a set of components, tools and guidance in Android Jetpack.

What is Android Jetpack Component ?

Android Jetpack components are a collection of libraries that are individually adoptable and built to work together while taking advantage of Kotlin language features that make us more productive.

These software components have been arranged in 4 categories which are as follows:

  • Foundation Components
  • Architecture Components
  • Behavior Components
  • UI Components

Let’s discuss one by one.

1. Foundation Components

Foundation components provide following cross-cutting functionality:

  • Backwards compatibility
  • Testing 
  • Kotlin language support.

All the foundation components are as follows:

  • App Compat: Degrade gracefully on older versions of Android with material design user interface implementation support.
  • Android KTX: Set of Kotlin extensions to write more concise, idiomatic Kotlin code.
  • Multidex: Provide support for multiple dex files for apps.
  • Test: A testing framework for unit and runtime UI tests in Android.

2. Architecture Components 

The architecture components help us in building:

  • Robust Apps
  • Testable Apps
  • Maintainable Apps

All the architecture components are as follows:

  • Data Binding: Declaratively bind UI elements to in our layout to data sources of our app.
  • Lifecycles: Manages activity and fragment lifecycles of our app.
  • LiveData: Notify views of any database changes.
  • Navigation: Handle everything needed for in-app navigation.
  • Paging: Gradually load information on demand from your data source.
  • Room: Fluent SQLite database access.
  • ViewModel: Manage UI-related data in a lifecycle-conscious way.
  • WorkManager: Manage every background jobs in Android with the circumstances we choose.

3. Behavior Components 

The behavior components help in the integration with standard Android services like:

  • Notifications
  • Permissions
  • Sharing
  • Assistant

All the behavior components are as follows:

  • Download Manager: Schedule and manage large downloads in background with auto retry support.
  • Media & playback: Backwards compatible APIs for media playback and routing (including Google Cast).
  • Notifications: Provides a backwards-compatible notification API with Wear and Auto support.
  • Permissions: Compatibility APIs for checking and requesting permissions in app.
  • Preferences: Create interactive settings screens for users to configure.
  • Sharing: Provides a share action suitable for an app’s action bar.
  • Slices: Create flexible UI elements that can display app data outside the app and can be extended all the way back to Android 4.4.

4. UI Components 

The UI components provide widgets and helpers to make your app not only easy, but delightful to use.

All the UI components are as follows:

  • Animation and transitions: Move widgets and transition between screens.
  • Auto: Components to develop Android Auto apps.
  • Emoji: Enable updated emoji font on older platforms.
  • Fragment: A basic unit of composable UI.
  • Layout: Lay out widgets with different algorithms.
  • Palette: Pull useful information from color palettes.
  • TV: Components to develop Android TV apps.
  • Wear: Components to develop Wear apps.

That’s all about Android Jetpack !!

Conclusion

In this article, We understood about the Android Jetpack Concepts. We learned the below Android Jetpack details:

  • What is Android Jetpack?
  • Why should we use ?
  • What Problem solves by Android Jetpack?
  • Types of Components in Android Jetpack
  • Components list and usage in Android Jetpack

Thanks for reading ! I hope you enjoyed and learned about the Android Jetpack Concepts. 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 and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

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!!???

React Native – Understanding Direct Manipulation

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about Direct Manipulation in React Native. Direct manipulation is an important concept in react native.

To understand the direct manipulation concept, we will discuss the below topics :

  • What is Direct Manipulation ?
  • How Direct Manipulation Works ?
  • UseCase using setState and setNativeProps

A famous quote about learning is :

” We now accept the fact that learning is a lifelong process of keeping abreast of change. And the most pressing task is to teach people how to learn.”

So, Let’s begin.


What is Direct Manipulation ?

The definition of Direct Manipulation says that 

Direct Manipulation is the process of making a component changes directly without using state/props or render whole hierarchies of components for a small change in one component.

Before the understanding of direct manipulation, we need to understand that how any components display on the UI Screen ?

The answer is that we need to write code for that components in render() method to display any component in the screen.

Now, what if you want to add/change any component?

The answer is we have to change state or props, otherwise the render() method will not be called. The render() method renders the whole component hierarchies even if there is a change in the only one component.

So the solution for this problem is Direct Manipulation that does not render all the component hierarchies for one component change.

In other way, we can say that

It is sometimes necessary to make changes directly to a component without using state/props to trigger a re-render of the entire subtree (or render the whole hierarchies of components for a small change in one component). This process is called Direct Manipulation.


How Direct Manipulation Works ?

In this section, we will see that how to work Direct Manipulation.

Direct Manipulation uses setNativeProps and Refs. setNativeProps is the react native equivalent to setting the properties directly on a DOM node.

and then, next question is “When to use setNativeProps and Refs ?”

Use setNativeProps when frequent re-rendering creates a performance bottleneck.

Direct manipulation will not be a tool that we reach for frequently; we will typically only be using it for creating continuous animations to avoid the overhead of rendering the component hierarchy and reconciling many views. setNativeProps is imperative and stores state in the native layer (DOM, UIView, etc.) and not within our React components, which makes our code more difficult to reason about. Before we use it, try to solve our problem with setState and shouldComponentUpdate.


UseCase

Let’s understand setNativeProps /Refs and setState concepts with one use case with the below code examples:

We have one TextInput which should be cleared when button is pressed.


1. Using setState

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

export default class App extends React.Component {

    constructor(props) {
      super(props)
      this.state = {
        inputText: '',
      }
    }
    clearText = () => {
        this.setState({
            inputText : ''
        })
    }

    render(){
        console.log("render method is called")
        return( 
        <View style={{justifyContent :'center',flex:1}}>
            <TextInput
            style={{height: 50,marginHorizontal: 20, borderWidth: 1, borderColor: '#ccf'}}
            value = {this.state.inputText}
            onChangeText= {(text) =>{
                this.setState({
                    inputText : text
                })
            }}
            />
            <TouchableOpacity onPress={()=>this.clearText()}>
                <Text>Clear Text</Text>
            </TouchableOpacity>
        </View>
        );
    }
}

In this above code example, we change the text or clear button each time. Render method is called which re-render the whole component even if there is a change for the component.


2. Using setNativeProps

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

export default class App extends React.Component {

    constructor(props) {
      super(props)
      this.state = {
        text: '',
      }
    }

    clearText = () => {
      this._textInput.setNativeProps({
        text: ' '
      });
    }

    render(){
        return( 
        <View style={{justifyContent :'center',flex:1}}>
            <TextInput
            ref={component => { this._textInput = component}}
            style={{height: 40,marginHorizontal: 18, borderWidth: 1, borderColor: '#ccc'}}
            onChangeText= {(text) =>{
                this._textInput.setNativeProps({text: text});
            }}
            />

            <TouchableOpacity onPress={clearText}>
                <Text>Clear Text</Text>
            </TouchableOpacity>
        );
    }
}

In above code example, render method will not be called when we click on clear text button or text is changed.

So Here the component will not be re-rendered. We can change any props of a component using setProps and Refs without using re-render().

Some times If we update a property that is also managed by the render function, we might end up with some unpredictable and confusing bugs because anytime the component re-renders and that property changes, whatever value was previously set from setNativeProps will be completely ignored and overridden. So we need to avoid conflict with the render function.

By intelligently applying shouldComponentUpdate, we can avoid the unnecessary overhead involved in reconciling unchanged component subtrees, to the point where it may be performant enough to use setState instead of setNativeProps.

That’s all about in this article.


Conclusion

In this article, We understood about Direct Manipulation in React Native. We also discussed how Direct Manipulation works with use-case. In Summary, we can say that :

  • Direct Manipulation is the process of making a component changes directly without using state/props.
  • Direct Manipulation helps to prevent render all the component hierarchies for one component change.
  • Direct Manipulation uses setNativeProps and Refs when frequent re-rendering creates a performance bottleneck.

Thanks for reading ! I hope you enjoyed and learned about the Direct Manipulation concepts in React Native. 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 and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

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