Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (Real DOM Vs Virtual DOM Vs Shadow DOM In JavaScript Frameworks).
In this note series, we will understand the differences between the Real DOM, Virtual DOM and Shadow DOM in JavaScript Frameworks.
So Let’s begin.
Real DOM Vs Virtual DOM Vs Shadow DOM
Real DOM
Virtual DOM
Shadow DOM
Definition
It is the representation of a document/webpage/web application’s user interface as a tree data structure (node and objects).
It is a virtual representation of the real DOM as a tree data structure (node and objects).
The Shadow DOM can be thought of as a “DOM within a DOM”. It is a separate DOM tree with it’s own elements and styles, fully separate from the main DOM.
Usage
The Real DOM is used in every browser.
The virtual DOM is employed in many front-end frameworks and libraries like React, Vue etc.
Web components use the concept of. Shadow DOM.
The purpose of each technology
It provides a simpler, more programmatic method of representing web pages.
The virtual DOM was created to address performance problems with webpages and web application that resulted from the constant re-rendering of the whole DOM whenever DOM elements were updated.
The Shadow DOM was designed to contain and isolate DOM elements, hence preventing direct DOM leakage of those elements and their dependent data.
Implementation
Real DOM is implemented on the browser.
Virtual DOM is utilized by frameworks and libraries such as React, Vue etc.
Shadow DOM is implemented on the browser.
Principle
The DOM represents the document/webpage as nodes and objects, allowing programming languages like javascript to interact with the page using an API.
The Virtual DOM is a tree representation of the real DOM using nodes and objects and is subsequently used as a blueprint to update the real DOM.
The Shadow DOM doesn’t comprehensively represent the whole DOM. Instead of adding DOM items to the main DOM tree, it inserts subtrees of DOM elements into the document.
Real DOM Vs Virtual DOM Vs Shadow DOM
Conclusion
In this note series, we understood about Real DOM, Virtual DOM and Shadow DOM differences and usages in JavaScript Frameworks. We also understood the DOM principles about Real DOM, Virtual DOM and Shadow DOM.
Thanks for reading! I hope you enjoyed and learned about the Real DOM Vs Virtual DOM Vs Shadow DOM In JavaScript Frameworks. 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 :
Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (Service vs IntentService In Android).
In this note series, we will understand the differences between the Service and IntentService in Android.
So Let’s begin.
Service
Service is an android component that is used to perform some long-running operations in the background, such as in the Music app, where we run the app in the background while using other mobile apps at the same time. The best part is that we don’t need to provide some UI for the operations to be performed in the background. By using Service, we can perform some InterProcess Communication(IPC) also. So, with the help of Service, we can perform a number of operations together because any application component can start a Service and can run in background.
There are three ways of using Service:
1. Foreground Service :
A foreground service is a Service that will let the user know about what is happening in the background. For example, in the Music application, the user can see the ongoing song on the device as a form of notification. So, here displaying notification is a must.
2. Background Service :
Here, the user will never know about what is happening in the background of the application. For example, whatsapp messenger compresses the image file to reduce the size while sending some images over whatsapp. This task is done in background and the user have no idea about what is going in the background. But for the API level 21 or higher, the Android System imposes some restrictions while using the Background Service. So, we take care of those restrictions before using the Background Service.
3. Bound Service :
The Bound Service is used when one or more than one application component binds the Service by using the bindService() method. If the applications unbind the Service, then the Service will be destroyed.
IntentService
The Service is the base class for the IntentService. Basically, it uses “work queue process” pattern where the IntentService handles the on-demand requests (expressed as Intents) of clients. So, whenever a client sends a request then the Service will be started and after handling each and every Intent, the Service will be stopped. Clients can send the request to start a Service by using Context.startService(Intent) . Here, a worker thread is created and all requests are handled using the worker thread but at a time, only one request will be processed.
To use IntentService, we have to extend the IntentService and implement the onHandleIntent(android.content.Intent).
Service vs IntentService
In this section, we will look upon some of the differences between the Service and IntentService, so that it will be easier for us to find which one to use in which condition. Let’s see the difference:
If we want some background task to be performed for a very long period of time, then we should use the IntentService. But at the same time, we should take care that there is no or very less communication with the main thread. If the communication is required then we can use main thread handler or broadcast intents. We can use Service for the tasks that don’t require any UI and also it is not a very long running task.
To start a Service, we need to call the onStartService() method while in order to start IntentService, we have to use Intent i.e. start the IntentService by calling Context.startService(Intent).
Service always runs on the Main thread while the IntentService runs on a separate Worker thread that is triggered from the Main thread.
Service can be triggered from any thread while the IntentService can be triggered only from the Main thread i.e. firstly, the Intent is received on the Main thread and after that, the Worker thread will be executed.
If we are using Service then there are chances that our Main thread will be blocked because Service runs on the Main thread. But, in case of IntentService, there is no involvement of the Main thread. Here, the tasks are performed in the form of Queue i.e. on the First Come First Serve basis.
If we are using Service, then we have to stop the Service after using it otherwise the Service will be there for an infinite period of time i.e. until our phone is in normal state. So, to stop a Service, we have to use stopService() or stopSelf() . But in the case of IntentService, there is no need of stopping the Service because the Service will be automatically stopped once the work is done.
If we are using IntentService, then we will find it difficult to interact with the UI of the application. If we want to out some result of the IntentService in our UI, then we have to take help of some Activity.
Conclusion
In this note series, we understood about Service and IntentService differences and usages in android. We also discussed about fundamental concepts of Service and IntentService. If we have some limited amount of tasks to be performed in the background, then we can use Service, otherwise, we can use IntentService.
Thanks for reading! I hope you enjoyed and learned about Service vs IntentService in Android. Reading is one thing, but the only way to master it is to do it yourself.
Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.
You can find Other articles of CoolmonkTechie as below link :
Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (Do And Don’t Valuable Checklist Summary Of React Component Lifecycle Methods).
In this note series, we will learn about the ReactJS Component Lifecycle methods checklist. And, this checklist points us to the principles of each lifecycle component method. So, this article will demonstrate the below React Component Lifecycle Methods checklist :
constructor
render
componentDidMount
componentDidUpdate
shouldComponentUpdate
componentWillUnmount
static getDerivedStateFromError
componentDidCatch
So Let’s begin.
1. constructor
DO
Assign the initial state to this.state directly.
Prepare all class fields and bind functions that will be passed as callbacks.
DON’T
Cause any side effects (AJAX calls, subscriptions etc.)
Call setState()
Copy props into state (only use this pattern if we intentionally want to ignore prop updates).
2. render
DO
Return a valid javascript value.
The render() function should be pure.
DON’T
Call setState()
3. componentDidMount
DO
Set up subscriptions
Network requests
May setState() immediately (Use this pattern with caution, because It often causes performance issues).
DON’T
Call this.setState as it will result in a re-render.
4. componentDidUpdate
DO
Network requests Incase if the props have changed otherwise not required.
May call setState() immediately in componentDidUpdate() ,but it must be wrapped in a condition.
DON’T
Call this.setState as it will result in a re-render.
5. shouldComponentUpdate
DO
Use to increase performance of components.
DON’T
Cause any side effects (AJAX calls etc.)
Call this.setState
6. componentWillUnmount
DO
Remove any timers or listeners created in the life span of the component.
DON’T
Call this.setState, start new listeners or timers.
7. static getDerivedStateFromError
DO
Catch errors and return them as state objects.
Handle fallback rendering.
DON’T
Cause any side effects
8. componentDidCatch
DO
Side effects are permitted
Log errors
DON’T
Render a fallback UI with componentDidCatch() by calling setState.
Conclusion
In this note series, We understood about DO and DON’T checklist of the ReactJS lifecycle methods.
Thanks for reading! I hope you enjoyed and learned about DO and DON’T checklist of the React lifecycle 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.
You can find Other articles of CoolmonkTechie as below link :
Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (iOS Best Practices And Swift Coding Standards With Code Organization, Spacing and Comments).
In this note series, we will learn about iOS Best Practices and Swift Coding Standards With Code Organization, Spacing and Comments. Coding standards act as a guideline for ensuring quality and continuity in iOS code. We will discuss about iOS best practices and swift coding standards with Code Organization, Spacing and Comments which will helps to ensure our code as efficient, error-free, simple ,easy maintenance enabled and bug rectification.
So Let’s begin.
Code Organization
We can use extensions to organize our code into logical blocks of functionality. Each extension should be set off with a // MARK: – comment to keep things organised.
Protocol Conformance
We can prefer adding a separate extension for the protocol methods when adding protocol conformance to a model. This keeps the related methods grouped together with the protocol and can simplify instructions to add a protocol to a class with its associated methods.
Preferred :
class MyViewController: UIViewController {
// class stuff here
}
// MARK: - UITableViewDataSource
extension MyViewController: UITableViewDataSource {
// table view data source methods
}
// MARK: - UIScrollViewDelegate
extension MyViewController: UIScrollViewDelegate {
// scroll view delegate methods
}
Not Preferred :
class MyViewController: UIViewController, UITableViewDataSource, UIScrollViewDelegate {
// all methods
}
Since the compiler does not allow us to re-declare protocol conformance in a derived class, it is not always required to replicate the extension groups of the base class.
This is especially true if the derived class is a terminal class and a small number of methods are being overridden. When to preserve the extension groups is left to the discretion of the developer.
For UIKit view controllers, consider grouping lifecycle, custom accessors, and IBAction in separate class extensions.
Unused Code
Unused (dead) code, including Xcode template code and placeholder comments should be removed. An exception is when our tutorial or book instructs the user to use the commented code.
Aspirational methods not directly associated with the article whose implementation simply calls the superclass should also be removed. This includes any empty/unused UIApplicationDelegate methods.
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return Database.contacts.count
}
Minimal Imports
Import only the modules a source file requires. For example, don’t import UIKit when importing Foundation will suffice. Likewise, don’t import Foundation if we must import UIKit.
Preferred:
//1
import UIKit
var view: UIView
var deviceModels: [String]
//2
import Foundation
var deviceModels: [String]
Not Preferred:
//1
import UIKit
import Foundation
var view: UIView
var deviceModels: [String]
//2
import UIKit
var deviceModels: [String]
Spacing
Indent using 2 spaces rather than tabs to conserve space and help prevent line wrapping. Be sure to set this preference in Xcode and in the Project settings as shown below:
Method braces and other braces (if/else/switch/while etc.) always open on the same line as the statement but close on a new line.
There should be exactly one blank line between methods to aid in visual clarity and organization. Whitespace within methods should separate functionality, but having too many sections in a method often means we should refactor into several methods.
There should be no blank lines after an opening brace or before a closing brace.
Colons always have no space on the left and one space on the right. Exceptions are the ternary operator ? :, empty dictionary [:] and #selector syntax addTarget(_:action:).
Long lines should be wrapped at around 70 characters. A hard limit is intentionally not specified.
Avoid trailing whitespaces at the ends of lines.
Add a single newline character at the end of each file.
We can re-indent by selecting some code (or Command-A to select all) and then Control-I (or Editor ▸ Structure ▸ Re-Indent in the menu). Some of the Xcode template code will have 4-space tabs hard coded, so this is a good way to fix that.
Preferred:
//1
if user.isHappy {
// Do something
} else {
// Do something else
}
//2
class TestDatabase: Database {
var data: [String: CGFloat] = ["A": 1.2, "B": 3.2]
}
Not Preferred:
//1
if user.isHappy
{
// Do something
}
else {
// Do something else
}
//2
class TestDatabase : Database {
var data :[String:CGFloat] = ["A" : 1.2, "B":3.2]
}
Comments
When we are needed, we can use comments to explain why a particular piece of code does something. Comments must be kept up-to-date or deleted.
We should avoid block comments inline with code, as the code should be as self-documenting as possible.
Exception: This does not apply to those comments used to generate documentation.
We should also avoid the use of C-style comments (/* … */). We can prefer the use of double- or triple-slash.
Conclusion
In this note series, we understood about iOS Best Practices and Swift Coding Standards With Code Organization, Spacing and Comments. We discussed about iOS Swift based Code Organization, Spacing and Comments concepts which will helps to ensure our code as efficient, error-free, simple ,easy maintenance enabled and bug rectification.
Thanks for reading! I hope you enjoyed and learned about Code Organization, Spacing and Comments concepts in iOS Swift. 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 :
Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (iOS Best Practices And Swift Coding Standards With Naming Conventions).
In this note series, we will learn about iOS Best Practices and Swift Coding Standards With Naming Conventions. Coding standards act as a guideline for ensuring quality and continuity in iOS code. We will discuss about iOS best practices and swift coding standards with Naming Conventions which will helps to ensure our code as efficient, error-free, simple ,easy maintenance enabled and bug rectification.
So Let’s begin.
Overview of Naming Conventions
Descriptive and consistent naming makes code easier to read and understand. We can use the swift naming conventions described in the API Design Guidelines. Some key takeaways include:
Striving for clarity at the call site
Prioritizing clarity over brevity
Using camel case (not snake case)
Using uppercase for types (and protocols), lowercase for everything else
Including all needed words while omitting needless words
Using names based on roles, not types
Sometimes compensating for weak type information
Striving for fluent usage
Beginning factory methods with make
Naming methods for their side effects
Verb methods follow the -ed, -ing rule for the non-mutating version
Noun methods follow the formX rule for the mutating version
Boolean types should read like assertions
Protocols that describe what something is should read as nouns
Protocols that describe a capability should end in -able or -ible
Using terms that don’t surprise experts or confuse beginners
Generally avoiding abbreviations
Using precedent for names
Preferring methods and properties to free functions
Casing acronyms and initialisms uniformly up or down
Giving the same base name to methods that share the same meaning
Avoiding overloads on return type
Choosing good parameter names that serve as documentation
Preferring to name the first parameter instead of including its name in the method name, except as mentioned under Delegates
Labeling closure and tuple parameters
Taking advantage of default parameters
Prose
When we refer methods in prose, being unambiguous is critical. We can refer method name in the simplest form as possible.
Write method name with no parameters. Example: Next, we need to call addTarget.
Write method name with argument labels. Example: Next, we need to call addTarget(_:action:).
Write the full method name with argument labels and types. Example: Next, we need to call addTarget(_Any?,action:Selector?).
For example using UIGestureRecognizer, Write method name with no parameter is unambiguous and preferred. We can use Xcode’s jump bar to lookup methods with argument labels. We can put the cursor in the method name and press Shift-Control-Option-Command-C (all 4 modifier keys) and Xcode will kindly put the signature on our clipboard.
Delegates
When we create custom delegate methods, an unnamed first parameter should be the delegated source. UIkit contains numerous examples of custom delegates methods.
We can use compiler inferred context to write shorter, clear code.
Preferred:
let selector = #selector(viewDidLoad)
view.backgroundColor = .red
let toView = context.view(forKey: .to)
let view = UIView(frame: .zero)
Not Preferred:
let selector = #selector(ViewController.viewDidLoad)
view.backgroundColor = UIColor.red
let toView = context.view(forKey: UITransitionContextViewKey.to)
let view = UIView(frame: CGRect.zero)
Generics
Generic type parameters should be descriptive, upper camel case names. When a type name doesn’t have a meaningful relationship or role, use a traditional single uppercase letter such as T, U, or V.
Swift types are automatically namespaced by the module that contains them and we should not add a class prefix such as RW.
If two names from different modules collide, we can disambiguate by prefixing the type name with the module name. However, we can only specify the module name when there is possibility for confusion which should be rare.
import SomeModule
let myClass = MyModule.UsefulClass()
Language
We can use US English spelling to match Apple’s API.
Preferred:
let color = “red”
Not Preferred:
let colour = “red”
Conclusion
In this note series, we understood about iOS Best Practices and Swift Coding Standards With Naming Conventions. We discussed about Naming Conventions which will helps to ensure our code as efficient, error-free, simple ,easy maintenance enabled and bug rectification.
Thanks for reading! I hope you enjoyed and learned about Naming Conventions concepts in iOS. 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 :
Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (An Overview Of Functions Currying In Kotlin).
In this note series, We will understand about Functions Currying in Kotlin. Currying is a common technique in functional programming. It allows transforming a given function that takes multiple arguments into a sequence of functions, each having a single argument.
In this short note series, we are going to implement an automatic currying mechanism that could be applied to any function taking three parameters.
So Let’s begin.
Overview
We can understand Currying as :
A common technique in functional programming.
Transforming a given function that takes multiple arguments into a sequence of functions, each having a single argument.
Each of the resulting functions handles one argument of the original (uncurried) function and returns another function.
To understand the concept of functions currying, let’s consider the following example of a function handling three parameters:
fun foo(a: A, b: B, c: C): D
Its curried form would like this :
fun carriedFoo(a: A): (B) -> (C) -> D
In other words, the curried form of the foo function would take a single argument of the A type and return another function of the following type: (B) -> (C) -> D. The returned function is responsible for handling the second argument of the original function and returns another function, which takes the third argument and returns a value of type D.
How To Implement it ?
In this section, we are going to implement the curried() extension function for the generic functional type declared as follows: ((P1, P2, P3). The curried() function is going to return a chain of single-argument functions and will be applicable to any function which takes three arguments.
Here, we can implement Functions Currying with the below steps :
Step 1 –Declare a header of the curried() function :
Let’s explore how to use the curried() function in action. In the following example, we are going to call curried() on the following function instance which is responsible for computing a sum of three integers:
fun sum(a: Int, b: Int, c: Int): Int = a + b + c
In order to obtain a curried form of the sum() function, we have to invoke the curried() function on its reference:
::sum.curried()
Then we can invoke the curried sum function in the following way:
val result: Int = ::sum.curried()(1)(2)(3)
Here, the result variable is going to be assigned an integer value equal to 6.
In order to invoke the curried() extension function, we access the sum() function reference using the :: modifier. Then we invoke the next functions from the function sequence returned by the curried function one by one.
The preceding code could be written in an equivalent more verbose form with explicit types declarations:
val sum3: (a: Int) -> (b: Int) -> (c: Int) -> Int = ::sum.curried()
val sum2: (b: Int) -> (c: Int) -> Int = sum3(1)
val sum1: (c: Int) -> Int = sum2(2)
val result: Int = sum1(3)
Under the hood, the currying mechanism implementation is just returning functions nested inside each other. Every time the specific function is invoked, it returns another function with the arity reduced by one.
Conclusion
In this note series, we understood about Functions Currying in Kotlin. Currying is useful whenever we can’t provide the full number of required arguments to the function in the current scope. We can apply only the available ones to the function and return the transformed function.
Thanks for reading! I hope you enjoyed and learned about Functions Currying in Kotlin. 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 :
Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (An Overview Of Android Foreground Service Launch Restrictions).
In this note series, We will understand about Android Foreground Service Launch Restrictions in Android 12.
Apps that target Android 12 can no longer start foreground services while running in the background, except for a few special cases. If an app tries to start a foreground service while the app is running in the background, and the foreground service doesn’t satisfy one of the exceptional cases, the system throws a ForegroundServiceStartNotAllowedException.
So Let’s begin.
Recommended alternative to foreground services
If our app is affected by this change, we can migrate to using WorkManager. WorkManager is the recommended solution for starting higher-priority background tasks.
Starting in WorkManager 2.7.0, our app can call setExpedited() to declare that a Worker should use an expedited job. This new API uses expedited jobs when running on Android 12, and the API uses foreground services on prior versions of Android to provide backward compatibility.
The following code snippet shows an example of how to use the setExpedited() method:
Because the CoroutineWorker.setForeground() and ListenableWorker.setForegroundAsync() methods are backed by foreground services, they’re subject to the same foreground service launch restrictions and exemptions. We can use the API opportunistically, but be prepared to handle an exception if the system disallows our app from starting a foreground service. For a more consistent experience, use setExpedited().
Cases where foreground service launches from the background are allowed
In the following situations, our app can start foreground services even while our app is running in the background:
Our app transitions from a user-visible state, such as an activity.
App can start an activity from the background, except for the case where the app has an activity in the back stack of an existing task.
Our app receives a high-priority message using Firebase Cloud Messaging.
The user performs an action on a UI element related to our app. For example, they might interact with a bubble, notification, widget, or activity.
Our app receives an event that’s related to geofencing or activity recognition transition.
After the device reboots and receives the ACTION_BOOT_COMPLETED, ACTION_LOCKED_BOOT_COMPLETED, or ACTION_MY_PACKAGE_REPLACED intent action in a broadcast receiver.
Our app receives the ACTION_TIMEZONE_CHANGED, ACTION_TIME_CHANGED, or ACTION_LOCALE_CHANGED intent action in a broadcast receiver.
App receives a Bluetooth broadcast that requires the BLUETOOTH_CONNECTor BLUETOOTH_SCAN permissions.
Apps with certain system roles or permission, such as device owners and profile owners.
Our app uses the Companion Device Manager. To let the system wake our app whenever a companion device is nearby, implement the Companion Device Service in Android 12.
The system restarts a “sticky” foreground service. To make a foreground service sticky, return either START_STICKY or START_REDELIVER_INTENTfrom onStartCommand().
The user turns off battery optimizations for your app. We can help users find this option by sending them to our app’s App info page in system settings. To do so, invoke an intent that contains the ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS intent action.
Conclusion
In this note series, we understood about Android Foreground services launch restrictions in Android 12. We discussed about cases where foreground service launches from the background are allowed.
Thanks for reading! I hope you enjoyed and learned about Foreground service launch restrictions in Android. Reading is one thing, but the only way to master it is to do it yourself.
Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.
You can find Other articles of CoolmonkTechie as below link :
Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (How To Disable Screen Rotation In React Native).
In this note series, we will learn how to Disable Screen Rotation In React Native. Handheld mobile devices always have two orientation mode Portrait mode and Landscape mode because of their design to hold in the hand. Portrait mode is by default mode in mobile devices, and if we rotate the device, it turns into Landscape mode.
So Let’s begin.
For Android Devices
Open Project -> android -> app -> src -> main ->AndroidManifest.xml .
Now, we have to put android:screenOrientation=“portrait” in AndroidManifest file.
After changing AndroidManifest.xml file, we need to re-run our project. This would disable the landscape mode in our current application in android devices.
For iOS Devices
Open Project ->ios -> Project_Name.xcodeproj file in XCode.
After opening the project in XCode, select project name.
Now Goto -> General -> Deployment Info and only select the Portrait mode.
Now Re-run our project. This would disable the landscape mode in our current application in iOS devices.
Conclusion
In this note series, we understood how to Disable Screen Rotation in React Native. This article showed the Disable Screen Rotation Steps in React Native.
Thanks for reading ! I hope you enjoyed and learned about Disable Screen Rotation 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 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 :
Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (Restart/Reset Current Screen In React Native Without Mounting It Again).
In this note series, We will learn how to Restart / Reset Current Screen In React Native without mounting it again. React Native does not provide the default refresh component to restart the screen. In some cases, we need to restart or reset the screen again. If we are using React Navigation then we have a choice to mount the screen again and to refresh the screen have a look at Refresh Previous Screen after Going Back in React Navigation but in the normal case, if we need to refresh the screen then react-native-restart can help us by providing RNRestart Component.
So Let’s begin.
To Import the Component
import RNRestart from 'react-native-restart';
To Restart or Reset The Current Screen In React Native
RNRestart.Restart();
Example
In this example, we are going to make a single screen with a setInterval which will update the counter in every second. We will have a button below the counter and on the press of the button, we will refresh the screen.
Example Project Setup
To demonstration of Restart/Reset Current Screen, we have to follow the below steps:
Create a new React Native project
Install the Dependency
Install CocoaPods
1. Create a new React Native project
Assuming that we have node installed, we can use npm to install the react-native-clicommand line utility. Open the terminal and go to the workspace and run
npm install -g react-native-cli
Run the following commands to create a new React Native project.
react-native init ProjectName
This will make a project structure with an index file named App.js in your project directory.
2. Install the Dependency
To install the dependencies, open the terminal and jump into our project
cd ProjectName
Now run the following commands to install the dependencies
npm install react-native-restart --save
3. Install CocoaPods
We need to install pods for the iOS
cd ios && pod install && cd ..
Example Code to Restart/Reset Current Screen In React Native
Now Open App.js in any code editor and replace the code with the following code.
// Restart/Reset Current Screen in React Native Without Mounting it Again
// import React in our code
import React, { useState, useEffect } from "react";
// import all the components we are going to use
import {
SafeAreaView,
Text,
View,
Button,
StyleSheet,
TextInput,
} from "react-native";
import RNRestart from "react-native-restart";
const App = () => {
const [value, setValue] = useState("");
useEffect(() => {
// Resetting default value for the input on restart
setValue("Default Value");
}, []);
const onButtonClick = () => {
RNRestart.Restart();
};
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={styles.container}>
<View style={styles.container}>
<Text style={styles.heading}>Example of React Native Restart</Text>
<Text style={styles.paragraph}>
Insert any value in Input and Click Restart Screen. You will see
blank TextInput again.
</Text>
<TextInput
placeholder="Please Insert Something"
defaultValue={value}
placeholderTextColor="#808080"
underlineColorAndroid="transparent"
onChangeText={(text) => setValue(text)}
style={styles.textInputStyle}
/>
<View style={{ marginTop: 20 }}>
<Button title="Restart Screen" onPress={onButtonClick} />
</View>
</View>
<Text
style={{
fontSize: 18,
textAlign: "center",
color: "grey",
}}
>
Restart/Reset Current Screen in React Native
</Text>
<Text
style={{
fontSize: 16,
textAlign: "center",
color: "grey",
}}
>
www.coolmonktechie.com
</Text>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "white",
padding: 10,
},
textStyle: {
textAlign: "center",
fontSize: 18,
color: "black",
},
heading: {
fontSize: 18,
fontWeight: "bold",
textAlign: "center",
},
paragraph: {
fontSize: 16,
marginVertical: 16,
textAlign: "center",
},
textInputStyle: {
fontSize: 25,
textAlign: "center",
height: 50,
backgroundColor: "#d6d6d6",
},
});
export default App;
To Run the React Native Example Code
Open the terminal again, and jump into our project using
cd ProjectName
To run the project on an Android Virtual Device or on real debugging device
react-native run-android
or on the iOS Simulator by running (macOS only)
react-native run-ios (macOS only).
The output of example code is as below:
After click the Restart Screen button, the output is as below :
Conclusion
In this note series, we understood how to Restart/Reset Current Screen in React Native Without mounting it again. This article showed the example code to Restart/Reset Current Screen in React Native.
Thanks for reading ! I hope you enjoyed and learned about Restart/Reset Current Screen 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.
You can find Other articles of CoolmonkTechie as below link :
Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (How Authentication Works In React Native ?) .
In this note series, we will learn how Authentication Works In React Native. Mostly Authentication is done by the OAuth2 Authentication Protocol in React Native application. This protocol is incredibly popular nowadays, prided as the most complete and secure protocol around. The OpenID Connect protocol is also based on this protocol.
So Let’s begin.
OAuth2 and Redirects
The OAuth2 authentication protocol is incredibly popular and the most complete and secure protocol around. In OAuth2, the user asks to the authenticate via a third party. On successful completion, this third party redirects back to the requesting application with a verification code which can be exchanged for a JWT — a JSON Web Token. JWT is an open standard for securely transmitting information between parties on the web.
PKCE (Proof of Key Code Exchange)
On the web, this redirect step is secure, because it guarantees URLs to be unique on the web. This is not true for apps because, as mentioned earlier, there is no centralized method of registering URL schemes! In order to address this security concern, an additional check must be added in the form of PKCE.
PKCE, pronounced “Pixy” stands for Proof of Key Code Exchange, and is an extension to the OAuth 2 spec. This involves adding a layer of security, which verifies that the authentication and token exchange requests come from the same client. PKCE uses the SHA 256 Cryptographic Hash Algorithm. SHA 256 creates a unique “signature” for a text or file of any size, but it is:
Always the same length regardless of the input file.
Guaranteed to be always produce the same result for the same input.
One way (that is, we can’t reverse engineer it to reveal the original input).
Now we have two values:
code_verifier – a large random string generated by the client.
code_challenge – the SHA 256 of the code_verifier.
During the initial /authorize request, the client also sends the code_challenge for the code_verifier , it keeps in memory. After the authorize request has returned correctly, the client also sends the code_verifierthat was used to generate the code_challenge. The IDP will then calculate the code_challenge, see if it matches what was set on the very first /authorize request, and only send the access token if the values match.
This guarantees that only the application that triggered the initial authorization flow would be able to successfully exchange the verification code for a JWT. So even if a malicious application gets access to the verification code, it will be useless on its own.
OAuth Library
A library to consider for native OAuth is react-native-app-auth. React-native-app-auth is an SDK for communicating with OAuth2 providers. It wraps the native AppAuth-iOS and AppAuth-Android libraries and can support PKCE. React-native-app-auth can support PKCE only if our Identity Provider supports it.
Conclusion
In this note series, we understood how Authentication works in React Native. We discussed the work flow of OAuth2 Authentication Protocol with PKCE in react native.
Thanks for reading ! I hope you enjoyed and learned about OAuth2 Authentication Protocol concept in React Native. Reading is one thing, but the only way to master it is to do it yourself.
Please follow and subscribe to the blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.
You can find Other articles of CoolmonkTechie as below link :