React Training
  • React JS Library
  • Roadmap
  • Training OutLine
  • React js basics
    • Understanding React JS
    • React JS a framework?
    • Setting Up React
    • Say Hello to React
    • Everything is a Component
    • Create-react-app
  • React Building Blocks
    • JSX and Babel
    • One Way Data Flow
    • Virtual DOM
    • V of MVC
    • React Terminology
    • React Tooling
  • Day 01
    • Day 01 OutLine
    • All About JSX
    • React Tools/ npm & webpack
    • Introduction of Webpack
    • Hello world using webpack
      • Webpack Setting up with React
    • NPM Scripts | Package JSON
      • Package.json file
    • React JS Principles
      • One Way Data Flow
      • V of MVC
      • Virtual DOM
    • Create React App - Part-1
    • Create React App - Part-2
  • Day 02
    • Quick Recap
      • Quiz
    • State & Props
      • State & Props in Depth
      • State Vs Props | Compare
    • React LifeCycle Methods
      • React LifeCycle Methods for V-0.16 x
    • Constructor | Lifecycle
    • Write Flicker App | First App
  • Day 03
    • Quick Recap
    • Life Cycle Flow
      • Birth and Mounting
      • Initlization and Construction
      • Pre Mounting
      • Render Method
      • componentDidMount
    • Type of React Components
      • Examples- Quick Compare
      • Class and Functional components
      • Functional Components
    • YouTube application
      • Component Design
    • All in One LifeCycle
  • Assignment
    • React App development
  • Day 04
    • Quick Recap on Lifecycle
    • Lifecycle deprecated/New Methods
      • New Lifecycle Methods
    • Lets Build App Netflix | Mock
  • Assignment
    • Github battle App | Assignment
  • Day 05
    • Quick Recap : Hooks
    • ES6 Features | Hands-on
      • ES6 Code Examples
    • Next Stop - React Router | SPA
      • Code examples | Router
      • React Router Building Blocks
      • Application using react-router-dom
  • Day 06
    • Router V4 | Quick Recap
    • ES2015 | 16 Quick Recap
    • LifeCycle Methods -Part-1
    • LifeCycle Methods -Part-2
  • Day 07
    • Quick Recap | New Lifecycle
    • Quick Recap | React Routing
    • Context API | React JS
      • component with context APIs
      • Context API | examples
    • App using Hooks/Context APIs
  • Assignment
    • Assignments
  • State Management Day-08
    • Quick Recap
    • Managing React State
      • What is Redux
      • Understanding Redux
      • Hello World "Redux"
  • React Redux Day - 09
    • Redux State Manager
    • Redux Redux Development
    • Simple Application | Redux
  • Redux Live Application Day -10
    • Redux with existing Application
      • Redux with React App
      • Lets Build More Apps
      • Should I use Redux from Dan
    • Quick Look at JS in React
    • Learn By Reading
  • miscellaneous Items - Day 11
    • Hooks useReducer
    • Hooks useContext
    • Hooks useRef
    • Hooks useEffect
    • Hooks useState
    • Lazy Loading and code splitting
    • Styling React Component
  • React Next Step - Day 12
    • Topics
    • Jest and Enjyme Testing
    • Examples: Testing
  • React Native
    • What is React Native
    • Setting up Environment
      • Linux Systems
    • React Native Hello World App
    • React Native Architecture
    • React Native Vs Native
    • Expo Cli or React Native CLI
  • React Native core Fundamental
    • React Native "Hello World"
    • Course OutLine
    • Getting started with Expo App
    • Layout with Flexbox
    • Working with Styles and Events
    • Manging Component State and Props
    • Build Simple Task List Application
  • What to Debug & How to Debug
    • Debug React Native Application
Powered by GitBook
On this page
  • Initialization & Construction
  • Default Props
  • Initial State

Was this helpful?

  1. Day 03
  2. Life Cycle Flow

Initlization and Construction

Initialization & Construction

During the initialization of the Component from the Element, the props and state are defined. How these values are defined depends on if you are using extend React.Component. Let's first look at props and then we will examine state.

Default Props

As we mentioned earlier, the Element instance contains the current props that are being passed to the Component instance. Most of the time, all the available props on the Component are not required. Yet, some times we do need to have values for all the props for our Component to render correctly.

For example, we have a simple component that renders a name and age.

import React from 'react';

export default class Person extends React.Component {
  render() {
    return (
      <div>{ this.props.name } (age: { this.props.age })</div>
    );
  }
}

In our case, we expect two props to be passed in: name and age. If we want to make age optional and default to the text 'unknown' we can take advantage of React's default props.

For ES6 Class

import React from 'react';

class Person extends React.Component {
  render() {
    return (
      <div>{ this.props.name } (age: { this.props.age })</div>
    );
  }
}

Person.defaultProps = { age: 'unknown' };

export default Person;

The result of either process is the same. If we create a new instance without setting the age prop ex: <Person name="Bill" />, the component will render <div>Bill (age: unknown)</div>.

Little bit in depth

// React library code to extract defaultProps to the Constructor
if (Constructor.getDefaultProps) {
   Constructor.defaultProps = Constructor.getDefaultProps();
}

// psuedo code (as an example)
this.props = Object.assign(Constructor.defaultProps, elementInstance.props);

In the React code snippet, React checks the underlying Class instance to see if it defines getDefaultProps() and uses this to set the values. When using ES6 classes we just define it on the class itself. Any property defined on the passedProps value is applied/overridden to the property in the default props object.

null vs. undefined props

When assigning default props, the React object merge code sees null as a defined value.

<Person name="Bob" age={ null } />

Because null is a defined value our Component would render this as <div>Bob (age:)</div>instead of rendering unknown. But, if we pass in undefined instead of null, React treats this as undefined (well yeah, obviously) and we would render unknown as expected.

Keep this in mind when defining default props, because tracing down a null value can be tricky in larger application.

Initial State

Once the final props are defined (passed w/ defaults), the Component instance configures the initial state. This process occurs in the construction of the instance itself. Unlike props, the Component state is an internal object that is not defined by outside values.

To define the initial state depends on how you declare your Component. For ES6 we declare the state in the constructor. Just like defaultProps, the initial state takes an object.

For ES6 Class

import React from 'react';

class Person extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  render() {
    return (
      <div>{ this.props.name } (age: { this.props.age })</div>
    );
  }
}

Person.defaultProps = { age: 'unknown' };

export default Person;

State defaults

It is important to keep in mind that if we do not define a state in the constructor then the state will be undefined. Because the state is undefined and not an empty Object ({}), if you try to query the state later on this will be an issue.

In general, we want to set a default value for all our state properties. There are some edge cases where the initial value for the state property may be null or undefined. If this state happens to be only state property, it may be tempting to skip setting a default state. But, if our code tries to access the property you will get an error.

 class Person extends React.Component {
  render() {
    // This statement will throw an error
    console.log(this.state.foo);
    return (
      <div>{ this.props.name } (age: { this.props.age })</div>
    );
  }
}

The log statement fails because this.state is undefined. When we try to access foo we will get a TypeError: Cannot read property 'foo' of null. To solve this we can either set the default state to {} or, to have a clearer intention, set it to { foo: null }.

PreviousBirth and MountingNextPre Mounting

Last updated 5 years ago

Was this helpful?

React handles default props by merging the passed props object and the default props object. This process is similar to or the Lodash/Underscore method. The default props object is the target object and the passed props is the source:

When using default props, it is important to understand how the React merge process works. Often, we are generating props dynamically based on application state (, , , etc.). This means that we can sometimes generate null values and pass this as the prop.

Object.assign()
_.assign()
Flux
Redux
Mobx