ReactJS

As a developer, I know I am always excited to learn the new, cool tech as soon as it comes out. Different people do it for different reasons; some do it to increase their knowledge bank, while for others it could be an add on to ease down their existing work and so on. That’s how I took my first step towards learning React.

The very initial stage for me was understanding how React was different and its benefits.

Basics of React

  1. Create interactive UI components and React renders it for you on any data change.
  2. It’s component based, build encapsulated components and they can manage their state.

React for beginners

What do we understand when we see the below statement.

const element = <h1>Hello, world!</h1>;

This is JSX an extension to Javascript that helps us create React Components. When we look at what our JSX code actually looks like on the execution.

const element = <h1>Hello, world!</h1>;
var appRoot = document.getElementById('app');  
ReactDOM.render(element,appRoot);

While it’s compiled it’s changed to:

var element = React.createElement("h1", null, "Hello, world!");  
var appRoot = document.getElementById('app');  
ReactDOM.render(element, appRoot);

Components, Props and State

The three main pillars of React are: components, props, and state. The entire code is built around these pillars. Elements are the smallest building blocks of React. Let’s start with creating a simple component and render the same.

import React from "react";  
import ReactDOM from "react-dom";

import "./styles.css";

function Counter() {  
  const count = 0;  
  return (  
    <div className="App">
      <h1>Counter:{count}</h1>
      <button>Increment</button>
      <button>Decrement</button>
      <button>Reset</button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Counter />, rootElement);

We have two types of components:

  1. Function Component: It accepts the props and returns a React Element. We also call it a functional stateless component because, being a simple JavaScript function, it does not allow the use of useState() in the component. They just receive input as props and return output as JSX: (props) => JSX. However, React Hooks made it possible to have a state in Function Components. I'll explain this towards the end.

  2. Class Component: It extends React.Component and creates a render function which returns a React Element.

So while we work on creating a presentational component, we must use a function component. For containers, we use class components.

React controls the data flow in the components with state and props. The data in states and props are used to render the Component with dynamic data. So the rule here says “Props go down(from parent to children) and events go up(from children to parent”).

Let’s take another example to understand props, events, and state.

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";
class Counter extends React.Component{
  constructor(props){
      super(props);
      this.handleaddOne=this.handleaddOne.bind(this);
      this.handleminusOne=this.handleminusOne.bind(this);
      this.handlereset=this.handlereset.bind(this);
      this.state={
          count:props.count
      };
  }
  handleaddOne(){
    this.setState((prevState)=>{
     return{
         count: prevState.count+1
     };
    });
 }
 handleminusOne(){  
     this.setState((prevState)=>{
     return{
         count: prevState.count-1
     };  
    });  
 }  
 handlereset(){  
    this.setState((prevState)=>  
    {  
return{  
 count:0  
};  
    });  
 }  
 render(){  
     return(  
     <div>  
       <h1>Count:{this.state.count}</h1>
       <button onClick={this.handleaddOne}>Increment</button>
       <button onClick={this.handleminusOne}>Decrement</button>
       <button onClick={this.handlereset}>Reset</button>
     </div>
 )};  
}

Lifting the State Up

Another major concept of React is Lifting the State Up. In React a component cannot pass information straight to its sibling. Instead, the information must travel through a common parent. The process of giving the correct components access to the right information is called lifting state. The props flow vertically down maintaining their local state, while at the same time there are multiple components that can share the same props. Hence maintaining the state both vertically and horizontally across the application gets tough. This is where lifting the state up comes into the picture. Here is a small demo for the same.

import React, { useState } from "react";
import ReactDOM from "react-dom";
import Button from "./Button";
import "./styles.css";

function App() {
  const [counter, setCounter] = useState(0);

  const incrementCounter = () => {
    setCounter(counter + 1);
  };

  return (
    <div className="App">
      <h1>Hello</h1>
      <Button
        counter={counter}
        onClick={() => {
          incrementCounter();
        }}
      >
        Example
      </Button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

The component is a Button :

import React from "react";
export default props => {
  return (
    <button onClick={props.onClick}>
      {props.children} clicked {props.counter} time
    </button>
  );
};

For another working demo on lifting state you can check out below link: Lifting State Source Code

Hooks

The above example also covers the concept of “Hooks” in React. Hooks help you in state management without the use of classes. I feel it’s a boon for the beginners who are trying to learn React as it eases down the state management. Hooks are even beneficial in code reusability, creating custom hooks helps us achieve that. But for now, we have plenty of them to explore like "useSate, useEffect, useRedux, useReducer etc".

Let's take examples for a few Hooks to get a better picture.

  1. useState: By importing useState in your code you’re signalling the intent to hold some kind of state inside your React component. And more important, that React component shouldn’t be an ES6 class anymore. It can be a pure and simple JavaScript function. This is the most appealing thing of the hooks story. Here is an example.
import React, {useState} from 'react';

function HooksDemo() {
  const [count, setCount] = useState(0);
  return (
    <div>
      Count: {count}
      <button onClick={() => setCount(0)}>Reset</button>
      <button onClick={() => setCount(count + 1)}>+</button>
      <button onClick={() => setCount(count - 1)}>-</button>
    </div>
  );
}
export default HooksDemo;

The first value, count in this case, is the current state (like this.state) and the second value setCount is a function used to update the state (first) value. The 0 in useState(0) function is the Initial Value of that particular state.

  1. useEffect: useEffect is similar to componentDidMount and componentDidUpdate of React Lifecycles.
function EffectHook() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

whenever you click on the button, the title text will change the number of counts. For example.. You clicked (n) times.

There are many exciting features that React offers us to explore. The topics I covered are some basic concepts that I learned as a beginner. I hope this helps people who are looking for a start.

This article was written by Megha Sachdev who is a Software Engineer at This Dot.

You can follow them on Twitter at @_megsachdev.

Need JavaScript consulting, mentoring, or training help? Check out our list of services at This Dot Labs.

Share