Advantages of React Stateless Functional Components

Advantages of React Stateless Functional Components

Before reading this post, if you have not gone through what are functional components in Reactjs then kindly go through this post

In this post we will see what are the advantages of functional posts in React js. If you check your react js code, you will quickly figure out that many components do not actually need state, they do get data from parent as props and will render the information. In such a case why to introduce state and make it complicated? rather I would prefer calling a function which returns me a component. Isn’t it so simple ? React 14 introduced Functional Components, also called as stateless components and removed unnecessary complications. So let us explore what are the advantages of stateless components 

Advantages of React Functional/Stateless Components: Ref

1. More focused on presentation

React is forcing us to write components which are used only for presentational purpose, these components are useful for dumb presentational purpose only, that focus on UI rather than behaviour. Technically speaking its normal tendency to go for stateful components, doing that way we are making our code easily hackable where every damn component keeps its own local state. Functional components allowing us to have pure components which just focus on presentation. where as the state is maintained by few higher level components.

2. Gain in Performance

Stateless components will bring performance gain since there is no state and lifecycle of a component. React doesn’t need to have unnecessary check and memory allocations which eventually brings performance boost.

3. Clean and Optimised Code

Stateless components reduce lot of code, almost 20% – 30% reduction in code and hence the code will become clean and optimised.

4. Easy to debug

Functional components are pure components and helps your to analyse your code quickly and you no need to put log if assert calls everywhere to debug. 

React more on React

React More on ReactNative 

React Native List View : Animate Rows While Scrolling Using FlatList

React Native List View : Animate Rows While Scrolling Using FlatList

In my previous post I have written about how to use React Native FlatList and we have seen the issues we face with pagination also how to add a loading indicator in the footer of FlatList. You can first read about it Link In this post we will see how to animate the rows while scrolling a FlatList.

Animating Rows In React Native FlatList :

To achieve animation for FlatList Rows, you have to install an npm module react-native-animatable, which provides variety of smooth animations for List Rows.

Installation of npm module:

$ npm install react-native-animatable --save


To make a continuous animation do this

<Animatable.Text animation="slideInDown" iterationCount={5} direction="alternate">Up and down you go</Animatable.Text>
<Animatable.Text animation="pulse" easing="ease-out" iterationCount="infinite" style={{ textAlign: 'center' }}>❤</Animatable.Text>


To animate rows in FlatList Rows do this

import * as Animatable from 'react-native-animatable';

class FlatListRow extends Component {
      <Animatable.View animation='fadeInUp'>;
          // here your row component

Variety of animations are supported in this React Native Animation library

ReactJS: Google Map Component

ReactJS: Google Map Component

Steps to implement google maps in Facebook’s ReactJS Web Application

1. Add npm module in your project for react-google-maps

npm install --save react-google-maps # or
yarn add react-google-maps


Reference :

Before this you have to include google maps api sdk in your index.ejs file 

<script src=”,geometry&key=<YOUR_API_KEY>”></script>

How to get Google Maps Api Key ? 

Follow the steps given in this link

2. Create Google Map Handler Component

'use strict';

import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import update from 'react-addons-update';

import canUseDOM from 'can-use-dom';

import raf from 'raf';
import GoogleMapComponent from './gMapComponent';

const geolocation = (
  canUseDOM && navigator.geolocation ?
  navigator.geolocation :
    getCurrentPosition(success, failure) {
      failure('Your browser doesnt support geolocation.');

class GoogleMapHandlerComponent extends React.Component {

    state = {
      bounds: null,
      center: null,
      content: null,
      radius: 400,
      markers: []

  constructor(props) {
    if (props !== null &&
        props !== undefined &&
        props.location !== null &&
        props.location !== undefined &&
        props.location.markers !== null &&
        props.location.markers !== undefined) {
      const locationInfo = {
        markers: props.location.markers
      this.state = locationInfo;

  componentDidMount() {
    const tick = () => {
      if (this.isUnmounted) {
      this.setState({ radius: Math.max(this.state.radius - 5, 0) });
      if (this.state.radius > 10) {
    geolocation.getCurrentPosition((position) => {
      if (this.isUnmounted) {
        center: {
          lat: position.coords.latitude,
          lng: position.coords.longitude,
        content: 'Location found using HTML5.',

    }, (reason) => {
      if (this.isUnmounted) {
        center: {
          lat: 60,
          lng: 105,
        content: 'Error: The Geolocation service failed (${reason}).',

    if (document.getElementsByClassName('pac-container').length > 0) {
      const gmapSearchResultsBox = document.getElementsByClassName('pac-container')[0]; = '2000';

  componentWillReceiveProps(nextProps) {
    if (nextProps !== null &&
        nextProps !== undefined &&
        nextProps.location !== null &&
        nextProps.location !== undefined &&
        nextProps.location.markers !== null &&
        nextProps.location.markers !== undefined) {
        markers: nextProps.location.markers

  componentDidUpdate() {
    if (document.getElementsByClassName('pac-container').length > 0) {
      const gmapSearchResultsBox = document.getElementsByClassName('pac-container')[0]; = '2000';
  componentWillUnmount() {
    this.isUnmounted = true;

  isUnmounted = false;

 handleMapMounted = this.handleMapMounted.bind(this);
 handleBoundsChanged = this.handleBoundsChanged.bind(this);
 handleSearchBoxMounted = this.handleSearchBoxMounted.bind(this);
 handlePlacesChanged = this.handlePlacesChanged.bind(this);
 handleMarkerClose = this.handleMarkerClose.bind(this);
 handleMarkerClick = this.handleMarkerClick.bind(this);

 handleMapMounted(map) {
     this._map = map;

   handleBoundsChanged() {
       bounds: this._map.getBounds(),
       center: this._map.getCenter(),

   handleSearchBoxMounted(searchBox) {
     this._searchBox = searchBox;
   handleLoadPlaces(markers) {

   handlePlacesChanged() {
     const places = this._searchBox.getPlaces();

     // Add a marker for each place returned from search bar
     const markers = => ({
       position: place.geometry.location,

     // Set markers; set map center to first search result
     const mapCenter = markers.length > 0 ? markers[0].position :;
       center: mapCenter,
     this.props.handleLocationChange(mapCenter, places);

   // Toggle to 'true' to show InfoWindow and re-renders component
  handleMarkerClick(targetMarker) {
      markers: => {
        if (marker === targetMarker) {
          if (marker.showInfo) {
            return {
              showInfo: false,
          return {
            showInfo: true,
        return marker;

  handleMarkerClose(targetMarker) {
      markers: => {
        if (marker === targetMarker) {
          return {
            showInfo: false,
        return marker;

  render() {
    return (
          <div style={{ height: '100%' }} />
          <div style={{ height: '100%' }} />

 function mapDispatchToProps(dispatch) {
   return bindActionCreators({ }, dispatch);

export default connect(null, mapDispatchToProps)(GoogleMapHandlerComponent);


3. Create Google Map Component, this component uses the components of react-google-maps module

'use strict';

import React from 'react';
import IconButton from 'material-ui/IconButton';

import {
} from 'react-google-maps';

import SearchBox from 'react-google-maps/lib/places/SearchBox';
import GoogleMapMarkerInfoWindow from './gMapMarkerInfoWindow';

import layoutStyle from '../../../constants/layoutStyle';

const INPUT_STYLE = {
  boxSizing: 'border-box',
  MozBoxSizing: 'border-box',
  border: '1px solid transparent',
  width: '240px',
  height: '32px',
  marginTop: '27px',
  marginRight: '20px',
  padding: '0 12px',
  borderRadius: '1px',
  boxShadow: '0 2px 6px rgba(0, 0, 0, 0.3)',
  fontSize: '14px',
  outline: 'none',
  textOverflow: 'ellipses',

const GoogleMapComponent = withGoogleMap(props => (
      inputPlaceholder='Search Location'

    {, index) => (
        onClick={() => props.onMarkerClick(marker)}
           Show info window only if the 'showInfo' key of the marker is true.
           That is, when the Marker pin has been clicked and 'onCloseClick' has been
           Successfully fired.
        {marker.showInfo && (marker.pinOnly === null ||
        marker.pinOnly === undefined || !marker.pinOnly) && (
          <InfoWindow onCloseClick={() => props.onMarkerClose(marker)}>
            <GoogleMapMarkerInfoWindow infoContent={marker.infoContent} />

    { && (
          fillColor: 'red',
          fillOpacity: 0.20,
          strokeColor: 'red',
          strokeOpacity: 1,
          strokeWeight: 1,

export default GoogleMapComponent;

4. Use Google Map Handler component whereever you wish to place the map

render() {
      const handleLocationChange = this.handleLocationChange;
      const mapsComponent = (
      return (
          style={{ width: '450px', height: '350px' }}

Note you have to pass your current location to land user on his current location, else any other location which is default location.
and a callback for handling change in location.

ReactJS google map location change callback will be called by react-google-maps library when there is change in location,
like user searched some location

Also check stateless react components :


Era of Artificial Intelligence : Facebook new algorithm to identify people

Era of Artificial Intelligence : Facebook new algorithm to identify people

Amost five years ago face recognition was a trend your mobile applications use to set ur face as password for your smartphones, Windows OS introduced face recognition to unlock the system, Facebook used face recognition for tagging people in the group photos. 

But Face recognition is now very old, technology is changing so fast that today’s technology will become out dated tomorrow. Every day something new coming to market, people are becoming more innovative than ever. Recognition ? what else can one do other than face and voice recognition ?

Identity of a person based on his unique characteristics

Every person will be having his own uniqueness in his characteristics, the way he dress, his hair style, his body shape, his standing posture what else ?. Identifying a person based on his characteristics can be achieved by properly analysing the data.

Facebook can recognise you in photos for tagging, even if you’re not looking

Facebook is experimenting on a new algorithm which can recognise a person based on his unique characteristics even though his face is not visible. Yann LeCun, head of artificial intelligence at Facebook, is leading a team of researchers. The team is analysing more than 40000 thousands photos from flickr and experimenting in the lab.

However there are certain privacy concerns raised by experts, but Facebook will surely find a way to keep things secured.

Read more about Future Technology : future-of-technology-imagine-the-future

Facebook Shows how artificial intelligence improve Facebook to show you perfect posts

Facebook has set up three AI labs so far, the company is investing enough time and effort on AI which helps Facebook to server the content that matches the people’s interest. Facebook revealed backend recognition tech in F8 conference. CTO Mike Schroepfer described new systems for identifying the content and context of videos and sentences.

Facebook working on secretly working on Language Technology Group and experimenting on recorded voices and converting it into text. It has been planned by Facebook to release the feature in Facebook messenger where it converts voice to text.

Facebook’s Video AI prototype

Facebook has developed video AI prototype that identify 485 types of sports but recognises tiny differences among games. See the video given below

AI can read sentences and determine things like who possesses what, or where is an object.

Check this experiment 🙂 AI recognises content from the Lord Of The Rings and able to answer question about the story.

Why AI Matters for Facebook ?

The one and only aim to understand the content, show the relevant content to the user. This is really very much required for Facebook like company because if some one else enter into the market with a new idea then people might start looking towards it. The only thing every one must focus on is never allow your user to think about something else.

Facebook, Google and Apple are really doing a great job in this aspect, Nokia once was a leading mobile phone manufacturers, but one product like iPhone killed Nokia. If you are an entrepreneur then you must learn a lesson out of it.

Also Read : An Interesting Article on how Facebook using aircrafts, laser beam to provide internet to remote areas on earth

Also Read : Interesting Article on How Facebook Using Artificial Intelligence, Facebook identifies you based on your hair style, your dressing, your standing posture

Also Read Windows 10 upgrade is available : See what you have to do if you can’t wait 🙂

Also Read : 8 Ways IOT will change your life .

Also Read : Is Google+ struggling ?

Think about it.

Regular Expressions : How Exactly they work internally ?

Regular Expressions : How Exactly they work internally ?

Regular expressions were playing major role in computers from several decades, they are not as simple as we think. They are need extensive computational power, a decade before regular expressions were a big headache for computer programmers and scientists because they were consuming lot of time to complete the task.

History behind Regular Expressions :

A neuroscientist  who tried to understand how the human brain could produce complex patterns using simple cells that are bound together. In 1943, Warren McCulloch and Walter Pitts published “A logical calculus of the ideas immanent in nervous activity”.  this paper had a great influence on computer science during that time. In 1956, mathematician Stephen Kleene developed this model one step further. In the paper “Representation of events in nerve nets and finite automata” he presents a simple algebra. The terms Regular Sets and Regular Expressions were born from then. As mentioned above, Kleene’s algebra had only two operations and one function. In 1968, the Unix pioneer Ken Thompson published the article “Regular Expression Search Algorithm” in Communications.

A Pattern in regular expression :

How to learn regular expressions ? How to understand regular expressions?. They look confusing to understand regular expression but regular expressions are an elegant way to do some string manipulations.

We have studied finite automata and the regular expressions all just works on this theory, but Most modern programming languages (Perl, Python, Ruby, Java (and JVM based languages), C#) do not use this approach rather they use recursive backtracking approach. But finite automata is really good to understand regular expressions with its state diagrams and not a bad idea to implement in this approach may be recursive backtracking is better. So do you need a help to understand regular expression? here it is…

Let us take one example, Validating an email address

If this is your regular expression


The respective state diagram might look like below

Regular expression state diagram
Regular expression state diagram

Regular expression parser Source Code

If you want to try out with your own regular expression code you can better go through here 

Tool to visualise your regular expression :

MIT’s Robot can jump over hurdles : Cheetah robot

MIT’s Robot can jump over hurdles : Cheetah robot

Human’s can achieve anything, human mind is the greatest gift of god. If you run in hurry or if you run on a moving floor your mind will get confused and some times you fell down. If you are not practiced then you can’t even cross two three hurdles continuously, you will fell down. Have you ever wondered a robot can do this ? it is so difficult to program even a simplest automation or even a simplest robot which can just move by itself. Now we have everything ready made so you may say it is not so difficult, but Cheetha which can run and jump over the hurdles ? really challenging.

A MIT’s Cheetah Robotic TEAM

Deborah Ajilo, Negin Abdolrahim Poorheravi,John Patrick Mayo,Justin Cheung, Sangbae Kim, Shinsuk Park, Kathryn L. Evans, and Matt Angle.  Will Bosworth, Joao Luiz Almeida Souza Ramos, Sehyuk Yim, Albert Wang, Meng Yee Chuah, and Hae Won Park.

Algorithm Behind MIT’s Cheetha robot :

The bounding algorithm which made this possible will program each of the robot’s legs to exert a certain amount of force in the split second during which it hits the ground, in order to maintain a given speed: In general, the faster the desired speed, the more force must be applied to propel the robot forward.

the cheetaha robot adopts the force as per the surface and hence it successfully passed the test in grassy area and treadmill.Robot can run 16 km/h, jump about 40 centimetres high, land safely and continue running for at least 15 minutes .

Technical Details of MIT’s Bounding Algorithm and Robotic Cheetah

It took more than 5 years to achieve this and Cheetah 2 contains the custom electric motor designed by Jeffrey Lang, the Vitesse Professor of Electrical Engineering at MIT and the amplifier designed by David Otten, a principal research engineer in MIT’s Research Laboratory of Electronics. 

“bounding algorithm” calculates the varying amounts of force required to propel an animal forward or to jump over obstacles. Algorithm models the running mechanics of world-class sprinters like Olympian Usain Bolt: the faster the desired speed, the greater the force the legs exert.

This robotic cheetah carries out its movements with the help of battery powered electric motors which do not make much noise even.  Though the US-military has been trying for several years to make a stealthy and fast robot, it hadn’t been successful until now so this DARPA funded research by the MIT researchers may just open a whole new vision regarding the making of a stealthier bot.


Android: ItemClickListner with CheckBox or RadioButton.

Android: ItemClickListner with CheckBox or RadioButton.

Lets take a scenario to understand the need of a listview which will have checkbox embedded in it.

Consider the flipkart mobile app, in that we want to compare 2 or more products, in order to do that I will go on selecting the items which I want to compare and then click on the compare button.


So we have multiple items in that and hence we cant use the android built in types for creating the list view. Hence we need to follow the below mentioned approach.


  1. Create an activity, which contains 2 listviews, one listview for displaying all available mobiles and another listview for displaying selected mobiles.
  2. Create an adapter for filling the mobile list for the above mentioned listviews.
  3. The layout which will be used for creating row which will make ItemClickListner work is as follows,





Observe the following attributes for Checkbox,


These make the checkbox non clickable and eventually the event will be transferred to its parent i.e the row and hence the ItemClickListner will be invoked.

You can download the files here

Animation and The Role of GPU – A Performance factor

Animation and The Role of GPU – A Performance factor

Just take a look into the given CSS which rotates your div by 360deg

.box_rotate {
 -webkit-transform: rotate(360deg); 
 -moz-transform: rotate(360deg); 
 -ms-transform: rotate(360deg); 
 -o-transform: rotate(360deg); 
 transform: rotate(360deg);

Code Example – JSFiddle

Have you ever wondered what happens in your computer when we see even a simple animation?

Your computer algorithm calculates every pixel and performs CPU intensive operation over each pixel. Ok what such operations it does ?. It calculates every pixel and performs Discrete Fourier Transformation on each pixel of the image. If your image is 512X512  = 2,62,144 pixels and the algorithms operates several frames per second, like 50 frames per second which depends upon the type of hardware/algorithm being used. It operates every pixel several times per second ( like every pixel 60 times per second ) now image for an image with size 512X512 = 2,62,144pixels and each pixel operated 60 times per second this gives you unbelievably huge number.

Assume that you operated only 1 second,

2,62,144 * 60 = 1,57,28,640 times and these many times it is not just a simple operation, they may apply Fourier transformation on each pixel. 

Another important factor to note that the Image rotation, Image scaling or any graphics related operations the the matrix calculations will come into picture. The rotation matrix and the image matrix will be multiplied to get the resulting image

rotation matrix
rotation matrix

An image matrix will be a huge one, like 512 x 512 x 3 for a given 512X512 image. the 3 in matrix indicates image is RGB coloured. It is not required to explain how matrix multiplications are CPU extensive, Theoretically, matrix-matrix multiplication uses O(N^3) operations on O(N^2) data

Comparison of GPU Matrix Multiplication operation over CPU

Why GPU and Why not CPU.

GPU are specifically made for performing graphics operations like moving pixels and applying transforms. Since CPU will be doing many more tasks like file operations, audio, calculations etc it is better to separate out your animated objects and give it to a different GPU layer. Imagine in the screen of 1024X800, somewhere some 200X100 size portion is animating, rather than giving 1024X800 space and find 200×100 space and then operate , it is nice trick to create separate layer of 200×100 space and perform animation independently in that layer.

So the load on your CPU will be reduced and the performance of the system will be improved. The difference between CSS3 and jquery animations are , CSS3 utilises GPU but jquery doesn’t, there another javascript based latest framework available called GSAP which is 20x faster than query. 


Comparison of jquery, CSS and GSAP Animation Performance :

Check our another article – how-to-make-you-web-site-faster-html-javascript-tricks

Reference :

How To Make You Web Site Faster : HTML , Javascript Tricks

How To Make You Web Site Faster : HTML , Javascript Tricks


The performance of your web application is highly important factor to get more user visits, experts have given many advices to improve the performance of a web application and few are listed below.

1. Meta refreshMeta refresh is a method of instructing a web browser to automatically refresh the current web page or frame after a given time interval, using an HTML meta element with the http-equiv parameter set to “refresh” and a content parameter giving the time interval in seconds.

Avoid Meta refresh as much as possible. This will slow down your site.

2. @imports will synchronously load the style sheet, Avoiding @import will improve the performance of your site. Instead of @imports use LINK tag as follows

<link rel=’stylesheet’ href=’knowledge-cess-style.css’>

Than   <style> @import url(‘knowledge-cess-style.css’); </style>

3. Avoid use of multiple framework – Some people use JQuery for some functionality and DOJO for some functionality . Loading of framework will take time and your app becomes heavy. Stick to one framework.

4. Placing scripts at the end

Most people will load all their scripts at the beginning of the page. Load scripts at the end, some times it is not possible, it gives an error if a function being used in the page. In that case make two js files and keep necessary stuff in one js and load it at the beginning.

5. Use ‘differ’ attribute to if some scripts must be loaded at the beginning.

<script src=“knowledge-cess.js” defer></script>

6. To construct dynamic pages it is better to use .innerHTML rather than always creating DOM elements dynamically.

7. Referencing more DOM elements using document.querySelectorAll()

var matches = document.querySelectorAll("div.note, div.alert"); Reference

8. Use Javascript timers carefully. Don't let timers run unnecessarily.
9. Javascript animation and Math

Time to play with Math now, animation is nothing but playing with frames, higher the frame rate smoother the animation and more frames means more processing. The time interval we set for an animation should depend on screen refresh rate.

Understand how Javascript Animation related to Screen refresh rate 

Most screens have refresh rate of 60Hz, so 60 frames per second (60fps) is best frame rate.
Javascript timer will be set in milliseconds. so considering 1000ms and 60FPS which will give
1000ms/60fps = 16.7ms. so it is best timer value, so set 16.7ms or 17ms for your javascript timer while playing with animations.

function setInterval(function(){

10. Performance factor for PNG and JPG – PNG will be of more size compared to jpg but jpg uses more complicated decoding algorithm compared to png.

Image format PnG vs JPG and performance
The reason png size will be more is because png format will use lossless compression algorithm and jpg will use lossy compression algorithm.
11. Using requestAnimationFrame : Mozilla team proposed requestAnimationFrame method to over come from performance issues in javascript animations. Have a look into this Link
There Many more performance tuning techniques.Now let us look into some best practices of javascript


Best Practices in Javascript

 1. Use Shortcut notations

var cities = ["Bangalore","Delhi","Mysore"]


var cities = new Array();

2. Keep related stuff together

Best Practice – 

var settings = function(){
     var userDefaults = {
         categories: {"defaultCategory" : "xyz", "lastCategory":"pqr"},
         modules : {}

      function initUserDefaults(){ }

      function clearUserDefaults(){}
   } //End of settings

The above way is clean and better approach rather than separating all methods.

3. Do not use primitive types as objects

 var name = "Ram";  //Best practice
      var name = new String("Ram"); //Not recommended

4. Use === operator

   Always use === operator for comparison, It always converts (to matching types) before comparison.

   The === operator forces comparison of values and type:

 100 == "100" //true which causes problem most of the times
      100 === "100" //false Best Practice, strict type checking

5. Global Variables in Javascript

Global variables are not recommended, Avoiding global variables is best practice.

6. Using JSLint 

Identify most common problems in your javascript code using JSLint tool


Check : how Animation in javascript works and how CSS3 is better than jQuerylink