Posted by : at

Category : react

React Components, State, Props and Lifecycle Methods

Components

Components let you split the UI in to independent, reusable pieces and think about each piece in isolation.

Conceptually, components are like Javascript functios. They accept arbitrary inputs( called “props”) and return React Elements describing what should appear on the screen.

The simplest way to define a component is to write a Javascript function:


function Welcome(props){
  return <h1> Hello, {props.name} </h1>;
}

This function is a valid React Component because it accepts a single “props” (which stands for properties) object argument with data and returns a React element. We call such components “function components” because they are literally JavaScript function.

We can define a component by :


class Welcome extends React.Component {
 render(){ 
   return <h1> Hello, {this.props.name} </h1>;
 }
}

Rendering a Component

React passes jsx attributes to this component as props.

function Welcome(props){
   return <h1> Hello, {props.name} </h1>;
}

const element = <Welcome name="Sujay" />;
ReactDOM.render(element, document.getElementById('root'));

Will Render “Hello, Sujay”

All React component must act like pure functions with respect to their props.

State

State is similar to props, but it is private and fuly controlled by the component

We use this.state inside our base constructor to declare the initial state.

And when we want to modify our state, we use this.setState()

for example consider the Ticking Clock functional Component, We want that clock should automatically update itself :


function Clock(props){
  return (
     <div>
        <h1> Hello, World! </h1>
        <h2> It is {props.date.toLocaleTimeString()}.</h2>
     </div>
  );
}

function tick(){
  ReactDOM.render(
    <Clock date={new Date()} />, 
     document.getElementById('root')
  );
}

// call the function
setInterval(tick,1000);

Lets convert this implementation, so clock can be a single component, that handles everything by itself by using state. We will define a new class for Clock rather than function.


class Clock extends React.Component{
   render(){
    return(
       <div> 
           <h1> Hello, World </h1>
           <h2> It is {this.props.date.toLocaleTimeString()}</j2>
       </div>
    );
   }
}

Whenever we use state, in a class. we need to pass the props to the base contructor. And we need to initialize new Constructor.

Constructor

React Constructors are only used for two purposes :

Initializing local state by assigning an object to this.state

Binding Event Handler Methods to an instance.

constructor(props){
   super(props);
  
   // set the initial state  
   this.state = " ";

}

Lets add now, some additional features like Local State to our Clock class. We will move the date from props to state :


class Clock extends React.Component{
  constructor(props){
      super(props);
      this.state = {date: new Date()};
  } 
  
  render(){
    return(
      <div> 
          <h1> Hello, World ! </h1>
          <h2> It is {this.state.date.toLocaleTimeString()} </h2>
      </div>
    );
  }
}

ReactDOM.render(<Clock />, document.getElementById('root'));

Lifecycle Methods

Now, we want to setup a timer, whenever the Clock is rendered to the DOM for the first time. This is called “mounting” in React.

We also want to clear that timer whenever the DOM produced by the Clock is removed. This is called “unmounting” in React.

So React has provided special methods, for our components lifecycle like :

  1. componentDidMount()
  2. componentDidUpdate()
  3. componentWillUnMount()

You can refer to this link -

Lifecycle Method Diagram

Mounting and Unmounting

componentDidMount - This Method runs after the component output has been rendered to the DOM.

componentWillUnmount - This Method runs before the component is removed from the DOM.

This is a good place to setup our timer:

So finally, our clock ticks every second !

Let’s quickly recap what’s going on and the order in which the methods are called:

1.When is passed to ReactDOM.render(), React calls the constructor of the Clock component. Since Clock needs to display the current time, it initializes this.state with an object including the current time. We will later update this state.

  1. React then calls the Clock component’s render() method. This is how React learns what should be displayed on the screen. React then updates the DOM to match the Clock’s render output.

  2. When the Clock output is inserted in the DOM, React calls the componentDidMount() lifecycle method. Inside it, the Clock component asks the browser to set up a timer to call the component’s tick() method once a second.

  3. Every second the browser calls the tick() method. Inside it, the Clock component schedules a UI update by calling setState() with an object containing the current time. Thanks to the setState() call, React knows the state has changed, and calls the render() method again to learn what should be on the screen. This time, this.state.date in the render() method will be different, and so the render output will include the updated time. React updates the DOM accordingly.

  4. If the Clock component is ever removed from the DOM, React calls the componentWillUnmount() lifecycle method so the timer is stopped.

Related Posts