DEV Community

Aravind Kumar
Aravind Kumar

Posted on

Part 1: React.js - Overview, Virtual DOM and State

React is one of the most popular JavaScript Framework on the Client side. In Part 1, we will be understanding the props, state and it's internal rendering process. Redux and Context API are conceptually different from React when it comes to handling of state, so we will be looking into those in Part 2 and 3 respectively.

Overview

create-react-app allows to build react projects. The entry point to the application is the index.js. Goal of React is render HTML in a web page. It uses ReactDOM.render() which takes two arguments, HTML Code and HTML element.
In index.js we can see this HTML Code is in form of <App /> and HTML element to be "document.getElementById('root')". App is the root/top most component in the component tree. While, the root element in index.html which is passed as second argument, will be appended by JSX code we write inside the components.

Components:
React is all about Components. Components, the building block of React are reusable and reactive in nature, they are written as JSX (custom HTML and Javascript) which are nothing but JavaScript methods called on React objects.

The tags in the JSX expression within the JavaScript file will be converted into createElement() by babel complier/transpiler.

Example:
JSX code:

let framework=
  <div className='library'>
    Hello, React!
  </div>
Enter fullscreen mode Exit fullscreen mode

Converted JavaScript equivalent:

let framework=
  React.createElement(
    'div',
    { className: 'library' },
    "Hello, React!"
  )
Enter fullscreen mode Exit fullscreen mode

Props:
Props or Properties are a system for passing data from "parent" to "child" components. Let's look at an example in which we will see how props can only be passed from parent to child but there is a bottom up way of approach where we can call a method in parent component from a child component.
Example:
Here AddName is a parent component and ClickName is a Child component. handleOnSubmit method reference is passed as a property from parent to child.

const AddName= () => {

  const handleOnSubmit = (name) => {
    concole.log("Rendered from AddName, called from ClickName with value: " + name);
  }

  return (
    <React.Fragment>
      <ClickName handleOnSubmit={handleOnSubmit} />
    </React.Fragment>
  )
}
Enter fullscreen mode Exit fullscreen mode

We will receive the props ClickName and call the parent function by using props.handleOnSubmit.

const ClickName = (props) => {
    return (
        <div>
            <button onClick={() => props.handleOnSubmit("React")}>
             Click Child
            </button>   
        </div>
    )
}
Enter fullscreen mode Exit fullscreen mode

//Output: From AddName, called from ClickName with value: React.

State

State are JavaScript objects that are relevant to a component. They must be initialized when they are created.

Example:

class demo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {title: "React", firstName: "Dev", lastName: "tools"};
  }
  render() {
    return (
      <div>
        <h1>Demo {this.state.title}</h1>
        <p>
          My name is {this.state.firstName}
          {this.state.lastName}.
        </p>
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

//Output: Demo React
My name is Dev tools.
State can be updated and when doing so the component gets re-rendered. To change the state always use the setState() method.

Example: From the previous demo example, let's add a method

changeTitleName() {
   this.setState({title: "Redux"});
}
Enter fullscreen mode Exit fullscreen mode

Inside the render method let's include a button below the paragraph,

render() {
    return (
      <div>
        <h1>Demo {this.state.title}</h1>
        <p>
          My name is {this.state.firstName}
          {this.state.lastName}.
        </p>
        <button
          type="button"
          onClick={this.changeTitleName}
        >Change Title</button>
      </div>
    );
  }
}

Enter fullscreen mode Exit fullscreen mode

This change in state triggers component's render() method, it's other lifecycle methods and causes re-rendering.

//Output: Demo Redux
My name is Dev tools.

Let us look into the React's way of re-rendering components before we see more about states.

Virtual DOM and State
It is React's virutal DOM which ultimately deals with the HTML elements in the screen. React on other hand notices the changes in state, that component that needs to be changed, the differences in previous state compared to the current state and these information are passed on the React's Virutal DOM. Virtual DOM then passes this information to the Real DOM which is part of the browser.
To sum up, the Primary feature that React care about are the data (props, state and component wide data). So, whenever the data change, components that use these data are basically updated and React lets virtual DOM know about these differences and the latest change is brought on to the screen after the browser's DOM gets the communication from virtual DOM.

Example:
Before update

<div> 
   <h2>React</h2>
</div>
Enter fullscreen mode Exit fullscreen mode

After update

<div> 
   <h2>React</h2>
   <h3>Only this content will be re-rendered</h3>
</div>
Enter fullscreen mode Exit fullscreen mode

React does diffing and let's virtual DOM know about the changes, virtual DOM then updates the browser's DOM to insert <h3>. The entire DOM will not be re-rendered.

Stateful and Stateless
State is similar to props, they are private to the component and it's fully controlled . Components can either maintain state which are Stateful or can remain stateless and contain no state in them.
Stateless components are simple functional components which try to print something or call some parent functions through props or render always the same thing. They are also called as dumb/presentational components.

Example:

const ProjectList = ({projects}) => {
 return (
   <Row>
     {projects.map(project => {
       return <Col>project</Col>
     })}
   </Row>
 )
}
Enter fullscreen mode Exit fullscreen mode

Stateful components keeps track of it's changing data. These components gets re-rendered on change of state. They are also called as Container/Smart components.

Example:

class Demo extends Component {
  constructor() {
    super()
    this.state = {
      titles: []
    }
  }
  render() {
    return (
      <div>
        <p>List of Titles</p>
        <Row>
          {this.state.titles.map(title => {
            return <Col>< {title} /></Col>
          })}
        </Row>
      </div>
    )
  }
}
Enter fullscreen mode Exit fullscreen mode

We coved some basic grounds in React. I hope this article was helpful. Thanks for reading :)

Top comments (0)