Thinking in React

I have been working in React, Flux and Redux for last few years and have gone through numerous success and failure experiences in it. This experience have given me a fare bit of knowledge on React and I thought of sharing it with you.

The major one which strikes me most is about “ thinking in react”, majority of new react developers have failed to adopt react as such because of the lack of “thinking in react way”.

avaScript and JavaScript class libraries and frameworks undergoes massive evolution for the past few years. React stood in front among that journey which allows us to develop rich client based highly performing single page applications.

Understand it correctly

The main part of learning react starts with understand the key things correctly. Props/State, life cycle events and the way of constructing a react component correctly. It is always good to have a basic understanding on what is happening behind the scene before start using the same. Try to get a basic knowledge of Reconciliation, Diff algorithm and the component tree then it is easy to understand that how the component get re-rendered , when we need to use or change props and state.

Understanding the life cycle events is really important because writing wrong thing in wrong event may end up in hell. Get a clear understanding on each life cycle like when it will get triggered and what action should we do in that. For example if you are writing some code to change the state unconditionally in componentDidUpdate() it will end up in an infinite re-rendering. Another example is attaching an event listener in didUpdate(), which will end up with n number of reference and the memory usage will rise.

Do you really need a state management mechanism by default?

No, is the answer. You don’t need one unless it is really painful for you to manage the state using private state. Nowadays there is trend like going for redux or any state management by default with every react project. Believe me , you can build cool apps with private state with less complexity and maintainability. The new Context API offers you great way to pass data from parent to grand child and which will help you to avoid unwanted props in intermediate components. I suggest you to think twice before you choosing a state management mechanism. Worth reading a good article from Dan Abramov on this here.

Understand your component structure

Ultimately you are going to create some html which will be rendering in the browser, keep this in mind while you are creating the components. A component does this for you in react, while render it will returns the html.Our aim here is to reuse the components as much as possible so design your component as tiny as possible. Once you got the html take a look and decide which all components need a state and which are not. Don’t go for a state until you really need that, avoid the hassles of state management by creating it as a stateless component.

Understand the new release Roadmap

React has their release Road map where they describes the journey towards asynchronous rendering and concurrent rendering. Keep this in mind because all the new releases coming with changes align with this road map. So we need to careful while developing our app and that should use the pattern or architecture which align with this road map so that it will be easy to upgrade to newer version and use those interesting features quickly.

Best practices in React and Flux


React is a wonderful class library which can be used to develop rich client application by ensuring better performance. Flux is the architecture which gives the beauty of uni-directional data flow and immutability of data. React+Flux is always a good choice while you starting your web application.I would like to share some thoughts on the good practices we can follow while developing an app using react and flux.

No direct store update

The unidirectional data flow gives the beauty of single source of truth, however it is a choice. Flux doing nothing to prevent you making it bidirectional, you can always update the store from your component directly with out initiating an action creator and action. If you want to follow flux don’t do this.

Call setState appropriately

One another mistake is calling setstate inside render. You can call setState anywhere other than render. However try to avoid unconditional setstate inside componentDidupdate() as it may lead to infinite re-rendering since didUpdate calls whenever a component has re-rendered.

Avoid updating the DOM directly and use ref wisely

Since react is doing the job of DOM update using virtual DOM it is a bad practice to update the DOM directly using conventional methods.Instead use ref to read the DOM and update the DOM react way by calling setState and re-rendering.

Always use unique key to the components

React internally identifies the components using key so it is important to make sure that you are using unique names for the react components.

vDo not add listeners in willReceiveProps or didUpdate().

Do not add event listeners in componentDidUpdate() and componentWillReceiveProps()

Adding event listeners in didUpdate and willReceiveprops is a bad idea as both life cycle events (willReceiveprops is deprecated from the latest version 16.4 onward) will trigger more than once based on props change or state change. So adding listeners in those event cause multiple reference of the event listeners and cause memory leak.

Stateless as much as possible and Tiny Components

It is always good to go for the stateless and tiny components whenever possible. This can improve the performance by avoiding the life cycle.

Bind the callback functions inside the constructor

Avoid binding the context while passing a call back function as prop to child component. If you are passing like that it will be creating a new reference every time and cause re-render of your pure child component. Instead bind the context in constructor and pass the same as prop.

class Parent extends React.Component{
    // Bind the context here
    this.callBackFunc = this.callBackFunc.bind(this)
    return ( <Child callBack={this.callBackFunc});

Introduction to ECMASCRIPT 2015 – ES6

Source code of examples (GitHub)


ECMASCRIPT 2015 aka ES 6 is the new ECMA standard standardized by Ecma International in ECMA-262 and ISO/IEC 16262. It makes java script lovers happy 🙂 . It adds lot of goodies to java script like classes, arrow functions,block scopes , const etc.


ECMASCRIPT is nothing but the standard. Almost all scripting languages including java script are created using ES (ES is using across this article for ECMASCRIPT) as core.

wiki link for history .

Browser Support

None of the browsers fully support ES 6. EDGE 13 supports 80% of ES 6 features and FF43 supports 72 %. You can check the complete list of browsers which support ES 6 here.

To overcome the browser support issue (only for time being) we can use transpilers to convert the ES6 code to ES5 and use them in your page. I am using babel transpiler in my examples to convert my ES6 code to ES5. There are many transpilers available. Have a look here .

What is new in ES6?

I would like to introduce some new goodies in ES 6 with examples in JavaScript.

1. Arrow functions

ES6 has arrow functions which has shorter syntax compared to normal function using the => syntax and are anonymous. They are syntactically similar to the related feature in C#, Java 8 and CoffeeScript. The synatx is:

// Basic syntax:
 (parameters) => { statements }
 (parameters) => expression
//  equivalent to: => { return expression; }



This will return squares of the given list of integer array. And the result is same as that of

[1, 2, 3, 4].map(function (x) {
 return console.log(x * x);

2. Constants

we can declare constants using the keyword const .

Example : const pi=3.14;

3. Template Strings

The beauty of string templates like String.Format() in C# is available in ES6. A tag can be added to create customized strings. Also it is possible to create multi line string without using ‘\n’.

Use back ticks (`) defining template strings. The sample code contains different ways of implementation

// Multi line strings
var multilineString =`In JavaScript this is
not legal.`

// String interpolation
var name = "Bob", time = "today";
console.log(`Hello ${name}, how are you ${time}?`);

We can also embed calculations in the string like below.

var taxPercentage = 10;
var price = 120;
console.log(`The tax is ${price*(taxPercentage/100)}`);

This will repalce the calculated value of price*(taxPercentage/100) in the string and return :

The tax is 12

And even functions too,

function calculateTotal(str,amt){
var taxPercentage = 10;
return str+(amt+(amt*(taxPercentage/100)));
var amt=120;
var msgWithTax= calculateTotal `The total amount is ${amt}`

This will create a string by calling the calculateTotal function and replaces the tag with calculated value and the result will be like below :

The total amount is ,132

4. Class

Yes, we can create class using the keyword class in java script. All java script lovers are happy to know js is now object oriented. 🙂

In the example below. I am creating a class with name Bake which has a constructor which accepts a cake type. The class has a member function named getTheCake which gives you the cake you wants.

class Bake {
   constructor(cake) {
      this.cake = cake;
   // Member function
   getTheCake() {

//Declaring objects of bake class
var a = new Bake('Plum cake');

//Assigining the variable.
a.cake='Choclate cake';

Here the first function call gives you a plum cake and the second gives you a Choclate cake. Enjoy the cake or create you own flavor.

5. inheritance

Since we already got classes there should be inheritance 🙂 , yes inheritance also there in ES6 using the keyword extends

class BakeWithFlavour extends Bake{
      console.log(`${this.cake} with ${this.flavour} flavour` );

Her BakewithFlavour class inherit from the Bake class . And its constructor calling the base constructor using super(cake).

let a = new BakeWithFlavour('Plum cake','choclate');

Here the function call getFlavouredCake() will give you a Plum cake flavored with chocolate. Enjoy your piece :).

6. Static methods

Like c# or java we can create static methods in ES6 using the keyword static. And these methods can be called using the class name itself.

class Bake {
   static getPlumCake(){
      return 'Plum cake';



ES 6 supports modules for component definition which is to support the standards of both common js modules and AMD (Asynchronous Module Definition – The most popular implementation of this standard is RequireJS ) . The synatx includes the key words export and import :

// module.js
 export function square(list[]) {>console.log(x*x));
//------ main.js ------
import {square} from 'Module';
// or you can use import * from 'module' to import all the members in module
var list=[1,2,3,4,5];

If we traspile this code using babel we need common.js implementation. Because bable is using the common.js module model to transpile the code.

In examples it contain both ES6 file as well as the transpiled file .I have used the transpiled js files in all. Try to use the actual ES 6 js files depends on your browser and enjoy the brand new java script with ES6 standards.


Reference 1

Reference 2

Please find the examples in GitHub here

Printing an rdlc report in a specific printer from an Asp.Net MVC application



Today I am sharing a small method which we have adopted for automatically printing an rdlc file in my Asp.Net MVC3 application upon a button client click.

During the development of an Asp.Net MVC application we had some bottlenecks in the printing of rdlc reports from the views. We were using the client definition (rdlc) of Reporting Service for report creation. But the things were stuck on one scenario where our client required to print the reports automatically by specifying a particular printer name which is presented. Upon clicking a button the reports need to be printed in a particular printer which was configured in the admin section.

After some analysis and googling we came to know that it is not a quick win. Finally we decided to achieve it with acrobat reader and java script in the pdf. (You must have an acrobat reader plugin installed in your browser)
As per our requirement, there is a printer setting where we are setting a particular printer for a particular report by providing the IP address of the system. According to these settings a particular report must print through a printer which is provided in the settings table upon clicking some button in the client.


First we have to design the report using rdlc. The next step is converting the rdlc to pdf from the action method in the controller. Also we need to inject a JavaScript for automatically printing the report in acrobat viewer. For that with the help of  iTextSharp we have converted the rdlc file into pdf at the same time we injected some JavaScript for automatic printing to the pdf.

You need to include the following namespaces which is in iTextSharp DLL
using iTextSharp.text.pdf;

The action method is as follows

public void RecieptPrint(long inv_ReceiptID)
      LocalReport localReport = new LocalReport();
      localReport.ReportPath = @"Reprt1.rdlc";
      DataTable dt = DataSelect();

            The following code is for dynamically setting the data source to rdlc. I already wrote about this here .

     ReportDataSource reportDataSource = new ReportDataSource();
     reportDataSource.Value = dt;
     reportDataSource.Name = "DataSet1";
     string reportType = "PDF";
     string mimeType;                  
     string encoding;
     string fileNameExtension = "pdf";
/* The DeviceInfo settings should be changed based on the reportType, here I have provided the size of the pdf based on my paper requirement. */

string deviceInfo =@”<DeviceInfo>
Warning[] warnings;
string[] streams;
byte[] renderedBytes;

Now we are going to converting the rdlc to byte array using the above device info for pdf .

renderedBytes= localReport.Render(reportType,deviceInfo,out mimeType, out   encoding, out   fileNameExtension,out streams,out warnings);

Here comes the important part of the solution. We are adding this byte array to our pdf file. Also we are injecting a JavaScript code which will execute upon loading the pf in thr reader and trigger the printing.

 var doc = new Document();
 var reader = new PdfReader(renderedBytes);
 using (FileStream fs = new FileStream(Server.MapPath(“~/Summary”+  Convert.ToString(Session[“CurrentUserName“]) + “.pdf“),     FileMode.Create))
     PdfStamper stamper = new PdfStamper(reader, fs);
     string Printer = "Printer_01"
     // This is the script for automatically printing the pdf in     acrobat viewer.
     stamper.JavaScript = “var pp = getPrintParams();
     pp.interactive = pp.constants.interactionLevel.automatic;    
     pp.printerName = ” + Printer + “;print(pp);\r”;

In view using an iframe or on a new window we can render this pdf and it will be printed automatically by executing the injected JavaScript.

Points of Interest

If we saved that pdf instead of printing while opening it will be printed automaticlay