React.js Fundamentals

What is React ?

React is a JavaScript library for creating user interfaces developed by Facebook . It is the V in MVC.

Simple

Simply express how your app should look at any given point in time, and React will automatically manage all UI updates when your underlying data changes.

Declarative

When the data changes, React conceptually hits the “refresh” button, and knows to only update the changed parts.

Build Composable Components

React is all about building reusable components. In fact, with React the only thing you do is build components. Since they’re so encapsulated, components make code reuse, testing, and separation of concerns easy.
Quick introduction video to React:


Simple component in React:

React component is a javascript function with minimum requirement that it should atleast have render() method. Render function should return a single react component.

Demo   ES6Demo

var Hello = React.createClass({
 render: function() {
 return <div > My name is {
 this.props.name
 } < /div>;
 }
});

ReactDOM.render( < Hello name = "Sam" / > ,
 document.getElementById('container')
);

JSX :

JSX is optional HTML like syntax that allows us to create a virtual DOM tree without using React.createElement(). As you can see in the example JSX allows us to write HTML like syntax in javascript code. This important as you can see what part of the component is HTML and what is pure javascript.

But this add additional complexity for JSX transformation step. Usually in the grunt tasks you can add this JSX transformation step. Babely is the most common module that transform JSX into javascript.

div className="red">Children Textdiv>;
MyCounter count={3 + 5} />;

// Here, we set the "scores" attribute below to a JavaScript object.
var gameScores = {
  player1: 2,
  player2: 5
};
DashboardUnit data-index="2">
  h1>Scoresh1>
  Scoreboard className="results" scores={gameScores} />
DashboardUnit>;

The above gets compiled to the following without JSX.

React.createElement("div", { className: "red" }, "Children Text");
React.createElement(MyCounter, { count: 3 + 5 });

React.createElement(
  DashboardUnit,
  { "data-index": "2" },
  React.createElement("h1", null, "Scores"),
  React.createElement(Scoreboard, { className: "results", scores: gameScores })
);

Props:

Props is a way for passing data from parent to child. This is way react communicate between the components always moving from top (parent) to bottom (child) (and not the other way around).

Demo

function RadioOption(props) {
return ({props.label})
}function renderChildren(props) {
return React.Children.map(props.children, child => {
if (child.type === RadioOption)
return React.cloneElement(child, {
name: props.name
})
else
return child
})
}

function RadioGroup(props) {
return (

{renderChildren(props)}

)
}

function WhereImUsingRadioGroups() {
return (

)
}
ReactDOM.render(
,
document.getElementById(‘container’)
);

Lifecycle events:

Sometime just render is not enough to create DOM. There is need for additional method that are needed before or after the render() method is called. React provides these methods to control the transformation from current component state to next component state.

A react component generally goes through three phases:

  • Mounting: When component is inserted into DOM.
  • Updating: Component is re rendering often result of virtual DOM computation.
  • Unmounting: Component being removed from the DOM.

Mounting: componentWillMount

void componentWillMount()

This method is invoked once, both on the client and server, before the initial rendering occurs. If you call setState within this method, render() will see the updated state and will be executed only once despite the state change.

Mounting: componentDidMount

void componentDidMount()

Invoked once, only on the client (not on the server), immediately after the initial rendering occurs. The componentDidMount() method of child components is invoked before that of parent components. This can be used for AJAX requests to the server.

Updating: componentWillReceiveProps

void componentWillReceiveProps(
  object nextProps
)

Invoked when a component is receiving new props. Use this as an opportunity to react to a prop transition before render() is called by updating the state using this.setState(). The old props can be accessed via this.props. Callingthis.setState() within this function will not trigger an additional render.

componentWillReceiveProps: function(nextProps) {
  this.setState({
    likesIncreasing: nextProps.likeCount > this.props.likeCount
  });
}

Updating: shouldComponentUpdate

boolean shouldComponentUpdate( object nextProps, object nextState ) 

This is invoked when new props or state are being received.

You should return false when you’re certain that the transition to the new props and state will not require a component update.

shouldComponentUpdate: function(nextProps, nextState) {
  return nextProps.id !== this.props.id;
}

If shouldComponentUpdate returns false, then render() will be completely skipped until the next state change. In addition, componentWillUpdate and componentDidUpdate will not be called.

By default, shouldComponentUpdate always returns true to prevent subtle bugs when stateis mutated in place, but if you are careful to always treat state as immutable and to read only from props and state in render() then you can override shouldComponentUpdate with an implementation that compares the old props and state to their replacements.

If performance is a bottleneck, especially with dozens or hundreds of components, useshouldComponentUpdate to speed up your app.This method is not called for the initial render or when forceUpdate is used.

Updating: componentWillUpdate

void componentWillUpdate(
  object nextProps, object nextState
)

Invoked immediately before rendering when new props or state are being received.

Use this as an opportunity to perform preparation before an update occurs.This method is not called for the initial render.You cannot use this.setState() in this method. If you need to update state in response to a prop change, use componentWillReceiveProps instead.

void componentDidUpdate(
  object prevProps, object prevState
)

Invoked immediately after the component’s updates are flushed to the DOM. This method is not called for the initial render.Use this as an opportunity to operate on the DOM when the component has been updated.

Unmounting: componentWillUnmount

void componentWillUnmount()

Invoked immediately before a component is unmounted from the DOM. Can be used to do some sort of cleanup like invalidating timer or remove any warning messages.

Example:

Demo

 var App = React.createClass({
/*setting state*/
getInitialState: function() {
return {
bgColor: “green”
};
},
/*changes state*/
handleColorChange: function (color) {
this.setState({ bgColor: color });
},
/*for the lifecycle methods*/
updateBackgroundColor: function () {
var body = document.querySelector(‘body’)
body.style.background = this.state.bgColor
},
/*lifecycle methods*/
componentDidMount: function () {
this.updateBackgroundColor()
},
componentDidUpdate: function () {
this.updateBackgroundColor()
},
render: function() {
return (

Hello, World!

What color?

)
}
});// ColorPicker component
var ColorPicker = React.createClass({
propTypes: {
value: React.PropTypes.string.isRequired,
onColorChange: React.PropTypes.func
},
handleChange: function(e) {
e.preventDefault();
var color = e.target.valueif (this.props.onColorChange)
this.props.onColorChange(color);
},
render: function() {
return (

orangered
teal
orange
indigo
red

)
}
});

React.render(, document.querySelector(‘#main’));

Virtual DOM

Virtual DOM is fast in memory representation of real DOM. It is the layer of abstraction that allows us to treat Javascript and DOM as they were reactive.

This is how it works:

  1. Whenever the state of the model changes , virtual DOM and React will render your UI.
  2. React then calculates the difference between two virtual DOM representations: the previous virtual DOM that computed before the data was changed and  current virtual DOM that is just computed after the data is changed.  The difference between the two DOM representations is what will actually be changed in the real DOM.
  3. React only updates difference calculated in step 2.

PS: You don’t need to worry about this calculation. It is all handled by React for you.


Mixins :

While writing different components you will realize there could be some code that is common between the components. This is also called as cross cutting concerns. Logging  or some sort of analytics is good example for such a use case.  In order to solve this problem so that you share your code between different components. React offers mixins.

Demo

 var SetIntervalMixin = {
componentWillMount: function() {
this.intervals = [];
},
setInterval: function() {
this.intervals.push(setInterval.apply(null, arguments));
},
componentWillUnmount: function() {
this.intervals.forEach(clearInterval);
}
};var TickTock = React.createClass({
mixins: [SetIntervalMixin], // Use the mixin
getInitialState: function() {
return {seconds: 0};
},
componentDidMount: function() {
this.setInterval(this.tick, 1000); // Call a method on the mixin
},
tick: function() {
this.setState({seconds: this.state.seconds + 1});
},
render: function() {
return (React has been running for {this.state.seconds} seconds.);
}
});ReactDOM.render(
,
document.getElementById(‘container’)
);

 Proptypes :

Proptypes is the range of validators that can be used to make sure the data that is  received in the component  is correct. When an invalid value is provided for a prop, a warning will be shown in the JavaScript console. You can also catch this error and throw some sort of error message.

Examples:

optionalArray: React.PropTypes.array, 
optionalBool: React.PropTypes.bool, 
optionalFunc: React.PropTypes.func,
optionalNumber: React.PropTypes.number,
optionalObject: React.PropTypes.object, 
optionalString: React.PropTypes.string, 
optionalSymbol: React.PropTypes.symbol

Read more on proptypes: https://facebook.github.io/react/docs/reusable-components.html

Flux :

Flux is the application architecture that Facebook uses for building client-side web applications. It complements React’s composable view components by utilizing a unidirectional data flow. It’s more of a pattern rather than a formal framework.

Flux applications have three major parts: the dispatcher, the stores, and the views (React components).

Flux eschews MVC in favor of a unidirectional data flow. When a user interacts with a React view, the view propagates an action through a central dispatcher, to the various stores that hold the application’s data and business logic, which updates all of the views that are affected. This works especially well with React’s declarative programming style, which allows the store to send updates without specifying how to transition views between states.

Redux:

Redux is a predictable state container for JavaScript apps. If you are handling data that does not have parent child relationship redux offers a elegant solution. If your application used many actions redux handle this well. If your application have same data used in multiple places redux is the solution. This is really the key point in using redux.

3 key principle of redux:

  1. Single immutable store.
  2. Action trigger changes.
  3. Reducers updates the state.

Flux vs Redux:

Similarities between Flux and redux:

  1. Both offer uni directional data flow (all data flows in same direction).
  2. Both utilize actions to define when state can be changed.
  3. Stores : Both have the concept of store which hold state of the application.

Differences between Redux and Flux:

  1. Reducers: are the function which takes current state and action and then return a new state.
  2. Containers : are just react components. It contains necessary logic for marshaling data and actions which is passed down to DOM components.
  3. Immutability: Redux store is immutable.

screen-shot-2016-09-10-at-10-50-03-pm

Flux Redux
Stores contain state and change logic Store and change logic are separate
Multiple stores Single store with hierarchical reducers
Flat and disconnected stores Single store with hierarchical reducers
Singleton dispatcher No dispatcher
React components subscribe to stores Container components utilize connect
State is mutated State is immutable

Sample Apps:

Real time Train tracking app :

Demo

This is a real time train time app build on just react. This demonstrate the concept of virtual DOM (the way data is updated is the table)

Sample flux app: Click here to view the project. This app is build on react and node.js. Use gulp to run the app. It uses facebook’s Flux architecture. Uses all Flux components such as Action,Dispatcher, Store.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s