Reader small image

You're reading from  ReactJS by Example - Building Modern Web Applications with React

Product typeBook
Published inApr 2016
Reading LevelIntermediate
PublisherPackt
ISBN-139781785289644
Edition1st Edition
Languages
Right arrow
Author (1)
Vipul A M
Vipul A M
author image
Vipul A M

Vipul A M is Director at BigBinary. He is part of Rails Issues Team, and helps triaging issues. His spare time is spent exploring and contributing to many Open Source ruby projects, when not dabbling with React JS. Vipul loves Ruby's vibrant community and helps in building PuneRb, is the founder of and runs RubyIndia Community Newsletter and RubyIndia Podcast, and organizes Deccan Ruby Conference in Pune. He can be found @vipulnsward on twitter and on his site http://vipulnsward.com.
Read more about Vipul A M

Right arrow

Chapter 3. Data Flow and Life Cycle Events

In the previous chapter, we saw the power of JSX. JSX makes it easy to write the React components.

In this chapter, we will focus on the data flow between components and how to manage state and life cycle of components.

In this chapter, we will cover the following points:

  • Data flow in React

  • Props

  • PropTypes

  • State

  • State versus props

  • When to use state and props

  • Component life cycle overview

  • Component life cycle methods

At the end of the chapter, we will get familiar with the data flow in the React components and the ways of maintaining and managing state. We will also get used to the life cycle of a component and various life cycle hooks provided by React.

Data flow in React


Shawn and Mark were getting ready to start working on a rainy day with a cup of coffee.

"Hey Mike, I have a question about props that we used to pass the headings and changeSet data to other components."

"Shoot!" Mike exclaimed.

"It seems to me that we are passing data to the components that are below the current component, but how can a component pass the data to the parent component?"

"Ah. In React, by default, all the data flows only in one direction: from parent component to child component. That's it."

This makes the job of the child component simple and predictable. Take props from the parent and render." Mike explained.

var RecentChangesTables = React.createClass({
  render: function(){
    return(<table className = 'table'>
             <Headings headings = {this.props.headings} />
             <Rows changeSets = {this.props.changeSets} />
           </table>);
    }
});

"Let's look at our example. The RecentChangesTables component passes the props...

Props validation


"React provides a way to validate the props using PropTypes. This is extremely useful to ensure that the components are used correctly. Here is an example of using propTypes for our app." explained Mike.

var App = React.createClass({
  propTypes: {
   headings: React.PropTypes.array,
   changeSets: React.PropTypes.array,
   author: React.PropTypes.string.isRequired
   },
  
  render: function(){
    return(<table className = 'table'>
             <Headings headings = {this.props.headings} />
             <Rows changeSets = {this.props.changeSets} />
           </table>);
    }
});

"Oh! Will it show an error as we are not passing the author, which is required, I assume? I see that propTypes has set the author value to be isRequired." Shawn asked.

"No. It will not throw an error, but it will show a nice warning for us to take a look at." said Mike.

"Also, propTypes are only checked in development. Their job is to just check that all the assumptions that...

Specifying default props


"Shawn, React also allows us to define some default values for props. This is useful when parent component is passing props based on some condition or not passing some props at all due to some change," Mike said.

var App = React.createClass({

 getDefaultProps: function() {
    return {
      headings: ['When happened ', 'Who did it', 'What they change']
    };
  },
  
  render: function(){
            …
  }
});

var data = [{ "when": "2 minutes ago",
              "who": "Jill Dupre",
              "description": "Created new account"
            },
            {
              "when": "1 hour ago",
              "who": "Lose White",
              "description": "Added first chapter"
            }];

React.render(<App changeSets={data}/>, document.body);

"Here, we updated the code to not send the headings from props. Instead, we used the getDefaultProps function to define the default props that will be used in case they are not passed."

"Therefore, our output...

Modifying this.props.children


"Shawn. There is one special prop that we should know about. It's this.props.children," continued Mike.

"React captures all the children that are present in the opening and closing tag into props that can be accessed through this.props.children." said Mike.

"Let's try to modify our code to use this.props.children. This is also required as we want to display a header for our output table." Mike added.

var RecentChangesTable = React.createClass({
  render: function(){
          return(
          <div>
            <h1> Recent Changes </h1>
            <table className='table'>
               {this.props.children}
            </table>
          </div>
          );
  }
});

var App = React.createClass({
  render: function(){
    return(<RecentChangesTable>
             <Headings headings = {this.props.headings} />
             <Rows changeSets = {this.props.changeSets} />
           </RecentChangesTable>);...

State


"Shawn, let's talk about one more technique of handling data in a component, state. Every component can have its own state in React. The main difference between state and props is that props are passed to the component from the parent component; whereas, state is something that is internal to the component.

Props are passed when a component gets instantiated. State is something that can change over time. Therefore, changes in state affect the rendering of components. Consider state as some sort of private data structure of the component." Mike added.

"Mike, but then we have not used state at all until now. We were just using props." Shawn asked.

"True. That is because state should be introduced only when it is required. You already know managing state is hard. As we were playing with static data of ChangeSets API, we didn't require state. However, we will need it very soon." Mike added.

Setting initial state


"The initial state can be set using the getInitialState function." said Mike.

var App = React.createClass({
  getInitialState: function() {
    return {
      changeSets: []
    };
  },
  
  render: function(){
    console.log(this.state.changeSets); // prints []  
});

"State can be accessed similar to props using this.state." Mike explained further.

Setting state


"We might need to update the initial state based on some user events. Updating state is also easy using the setState() function." informed Mike.

var App = React.createClass({
  getInitialState: function() {
    return {
      changeSets: [],
      headings: ['Updated At', 'Author', 'Change']
    };
  },
  
  handleEvent: function(data) {
    this.setState({ changeSets: data.changeSets });
  },
  
  render: function(){
    …    
});

Avoiding state


"Currently, we don't need state; however, when we fetch the dynamic data from RecentChanges API, we will use state with props." Mike added.

"Cool. Based on our discussion, I think that we should avoid state as much as possible." Shawn suggested.

"True. If a component does not change, then there is no need to use state. It's better to depend on props passed by the parent component in that case. This also avoids re-rendering of the component again and again as changes to state initiate a re-render of the component." Mike explained.

State versus props


"Shawn, it's important to understand the difference between props and state and where to use what." informed Mike.

"Props are immutable. They should not be updated by the component to which they are passed. They are are owned by the component which passes them to some other component. State is something internal and private to the component. State can and will change depending on the interactions with the outer world." said Mike.

"State should store as simple data as possible, such as whether an input checkbox is checked or not or a CSS class that hides or displays the component." Mike added.

"Another thing to make sure is to not duplicate props in state." said Mike.

var App = React.createClass({
  getInitialState: function() {
    return {
      changeSets: this.props.changeSets
    };
  }
});

"It is possible to set the state based on data passed in props. However, the parent component can update the props and send them again. In this case, the state will be muddled up with...

Component life cycle overview


"Shawn, now let's start taking a look at how to dynamically fetch data from https://openlibrary.org/, store it in our component, and render it after making it compatible to render.

A component goes through different life cycle events. They help facilitate when we should initialize which part of a component or when should some external data be fetched.

We have already seen some of these methods such as render, getInitialState, and getDefaultProps.

An updated detailed list and example for the same can be found at http://videos.bigbinary.com/react/react-life-cycle-methods-in-depth.html.

Let's go through each of these, one by one, and how they can be used so that we can start fetching dynamic information for display. Here is a list of methods that we will discuss:

  • componentWillMount

  • componentDidMount

  • componentWillReceiveProps(object nextProps)

  • boolean shouldComponentUpdate(object nextProps, object nextState)

  • componentWillUpdate(object nextProps, object nextState...

Component life cycle methods


"Shawn, let's start with an exhaustive example that triggers these methods." Mike informed.

console.log('Start') // Marks entry point of JS code.
var App = React.createClass({
    componentWillMount: function(){
      console.log('componentWillMount');
    },
    
    componentDidMount: function(){
      console.log('componentDidMount');
    },
    
    getInitialState: function(){
      return { status: true}
    },

    getDefaultProps: function(){
      return {name: 'John'};
    },
  
    componentWillReceiveProps: function(nextProps){
      console.log('componentWillReceiveProps');
    },

    shouldComponentUpdate: function(nextProps, nextState){
      console.log('shouldComponentUpdate');
      return true;
    },
    
    componentWillUpdate: function(){
      console.log('componentWillUpdate');
    },
    
    render: function() {
      console.log('render');
      return <h1 onClick={this.toggleState}>    
             {this.state.status.toString...

Summary


In this chapter, we looked at how to pass around data in the React components using props and state. We also discussed how and when to use state and props. We looked at how propTypes can be used to validate the props. After that, we discussed the component's life cycle. We discussed about the various life cycle methods and how they can be used. After that, we used these life cycle methods to get real-time data from Open Library API.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
ReactJS by Example - Building Modern Web Applications with React
Published in: Apr 2016Publisher: PacktISBN-13: 9781785289644
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Vipul A M

Vipul A M is Director at BigBinary. He is part of Rails Issues Team, and helps triaging issues. His spare time is spent exploring and contributing to many Open Source ruby projects, when not dabbling with React JS. Vipul loves Ruby's vibrant community and helps in building PuneRb, is the founder of and runs RubyIndia Community Newsletter and RubyIndia Podcast, and organizes Deccan Ruby Conference in Pune. He can be found @vipulnsward on twitter and on his site http://vipulnsward.com.
Read more about Vipul A M