Mar 28, 2020

Textual description of firstImageUrl

React components and life cycle: Stateful and stateless, Class-based and functional component & Class component life cycle.

React component can be classified in two category: Class(or Container) based component and Functional (or presentational) component. Historically(before ReactVersion 16.8) class based component has been considered stateful component and functional component is stateless component. From React-16.8 functional component can manages state using React Hooks useState().

A good strategy for React application is to restrict state management with very few component (ideally class based) and presentational component should be dependent on props and it makes presentational component more reusable.

Class based and functional component: Class based and functional component can be differentiated in following ways.

1. Class and functional component Syntax: Class-based component extends Component and function component is represented as function.
Functional component 
import React from 'react';

const contact = (props) => (
  <div>
    <h1>{props.title}</h1>
  </div>
);

export default contact;
Class-based component 
import React, { Component } from 'react';
import './Checkout.css';

class Checkout extends Component {
    state = {
        loggedInCustomer: null,
        guestCustomer:null
    }
  render() {
    return (
      <div className="Checkout">
        {/* manages state of app...  */}
      </div>
    );
  }
}

export default Checkout;

2. State accessibility and life cycle hooks: Both class-based component and functional component(From react 16.8) can access state. But only class based component has life cycle hooks. Life cycle hooks provides ability to modify state before and after loading components.
  • Class-based component access state and props via "this" and 
  • Functional component access state using useState() and Properties using props.
Class-component accessing state and props:
this.state.property-1 
this.props.property-2


Class component life cycle

Component Create life cycle: Create component life cycle starts from constructor() and ends at componentDidMount() methods. Both constructor() and componentDidMount() are optional methods, render() method must be defined to full component creation cycle.
Sample App.js to demonstrate component create cycle:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Checkout from './containers/Checkout';

class App extends Component {
  /*Step-1: Constructor */
  constructor(props){
    super(props);
    console.log('[App.js] constuctor');
  }
  state = {
    orders:[
      { upc: '007410134707', productName: 
        'Fujifilm Instax Mini 7S Instant Camera', unitPrice: "210" },
      { upc: '007410134708', productName: 
      'Monitor 43 Inch', unitPrice: "340" }
    ]
  }

  /* Step-2: getDerivedStateFromProps */
  static getDerivedStateFromProps(props,state){
    console.log('[App.js] getDerivedStateFromProps', props,state);
    return state;
  }

  /* Step-3: Execute render method */
  render() {
    console.log('[App.js] render() execution');
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          My First React App !!
        </p>
        {/* Render Child component Checkout */}
        <Checkout/>
      </div>
    );
  }

  /* Step-4: Execute componentDidMount: 
             make HTTP call at this point.... */
 componentDidMount(){
  console.log('[App.js] componentDidMount execution');
 }
}

export default App;

Component creation journey with child component Checkout 
Component update life cycle: Update component life cycle is more complex and has additional states. Update component life cycle pays important role in improving performance of application.

import React, { Component } from 'react';

class Checkout extends Component {
    /*Step-1: getDerivedStateFromProps: This will throw warning when loaded as initial satte is empty */
    static getDerivedStateFromProps(props,state){
        console.log('[Checkout.js] getDerivedStateFromProps');
        return state;
    }
    /* Step-2: Should return boolean(true/false) based on some condition */
    shouldComponentUpdate(nextProps, nextState){
        console.log('[Checkout.js] shouldComponentUpdate');
        /* Shalllow comparision not deep */
        if(nextProps.orders !== this.props.orders)
            return true;
        return false;
    }
    
    state = {
        loggedInCustomer: null,
        guestCustomer:null
    }
  /* Step-3: */
  render() {
    console.log('[Checkout.js] render() execution');
    return (
      <div className="Checkout">
        {/* manages state of Checkout...  */}
      </div>
    );
  }

    /* Step-4: Used to some operation before componentDidUpdate like gettting scrolling co-ordinate. 
        Save some data before udpate state.*/
    getSnapshotBeforeUpdate(prevProps, prevState){
            console.log('[Checkout.js] getSnapshotBeforeUpdate');
        return {message:'Snapshot!!'};
    }
        
        
  /* Step-5: */
  componentDidUpdate(prevProps, prevState,snapshot){
    console.log('[Persons.js] componentDidUpdate');
    console.log(snapshot);
}
}

export default Checkout;

Functional component with useEffect and setState
: Functional component does not have life cycle as class based component. Functional component uses React hooks to update state & execute certain method on every load of functional component.

Location: Sunnyvale, CA, USA

1 comment:

  1. Big data is a term that describes the large volume of data – both structured and unstructured – that inundates a business on a day-to-day basis. big data projects for students But it’s not the amount of data that’s important. Project Center in Chennai It’s what organizations do with the data that matters. Big data can be analyzed for insights that lead to better decisions and strategic business moves.

    Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Corporate TRaining Spring Framework the authors explore the idea of using Java in Big Data platforms.
    Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai


    The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

    ReplyDelete