Monthly Archives: May 2021

React – Functional Components VS Class Components

1. Syntax

A functional component is a plain JavaScript function that returns JSX, where the class component is a JavaScript class that extends React.Component which has a render method.

2. Extend component

Whenever a class component is created, it is necessary to extend the component, however, if a functional component is created, it is not necessary to extend the component. With functional components, we can use props directly.

Functional component example

// Using ES6 arrow functionimport React from "react"; const FunctionalComponent = () => { return <h1>Elephant Solutions</h1>;};

Class component example

// Using destructuringimport React, { Component } from "react";​class ClassComponent extends Component { render() {   return <h1>Elephant Solutions</h1>; }}

3. Access state

Previously, access to the state was possible only through class components, which was the main difference between class and functional components. But with the advent of useState, it is possible to manage the state through functional components as well. However in that case we always have to use useState React Hook. From React version 16.8 useState React Hook was introduced to allow developers to write stateful functional components.

Functional component example

// Using functional component with the useState React Hook to handle the state// Without ES6 arrow functionimport React, { useState } from 'react';​function FunctionalComponent() {  const [count, setCount] = useState(0);​  return (    <div>      <p>You clicked {count} times</p>      <button onClick={() => setCount(count + 1)}>        Click me      </button>    </div>  );}

Class component example

// Handling state using the class componentclass ClassComponent extends React.Component {  constructor(props) {    super(props);    this.state = {      count: 0    };  }​  render() {    return (      <div>        <p>You clicked {this.state.count} times</p>        <button onClick={() => this.setState({ count: this.state.count + 1 })}>          Click me        </button>      </div>    );  }}

4. Use of “this” keyword

Whenever we try to access props or state using class components we need to use the “this” keyword. However, it is not necessary to use the “this” keyword for functional components.

Functional component example

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

Class component example

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

5. Lifecycle methods

Lifecycle plays a big role when it comes to the timing of rendering. For class components, we had a method like componentDidMount() that was called immediately after the first render was completed, componentWillMount() that was called before the first rendering, however, this method is considered legacy, so it is not recommended to use this method in newer versions of React and we also had componentDidUpdate() which was invoked immediately after updating occurs. It’s a lifecycle method that runs every time a component gets new props, or a state change happens. This method is not called during the initial rendering.

When we talk about functional components, there is a hook that is great for this purpose. React useEffect Hook serves the same purpose as componentDidMount(), componentDidUpdate() and componentWillUnmount().

Functional component example

import React, { useState, useEffect } from "react";​export default function FunctionalComponent() {  const [data, setData] = useState([]);​  useEffect(() => {    fetch("http://localhost:3001/movies/")      .then(response => response.json())      .then(data => setData(data));  }, []);​  return (    <div>      <ul>        {data.map(el => (          <li key={el.id}>{el.title}</li>        ))}      </ul>    </div>  );}

Class component example

import React, { Component } from "react";​export default class ClassComponent extends Component {  state = { data: [] };​  componentDidMount() {    fetch("http://localhost:3001/movies/")      .then(response => response.json())      .then(data =>        this.setState(() => {          return { data };        })      );  }​  render() {    return (      <div>        <ul>          {this.state.data.map(el => (            <li key={el.id}>{el.title}</li>          ))}        </ul>      </div>    );  }}

Conclusion

How do we decide which component to use? There is no need to decide which components to use, functional components are the way to go. Then why is it important to know these differences if we do not intend to write class components?

The thing is that not so long ago we had class components everywhere. There are still React applications that use class components. This way we will have a generally better understanding of the React library. Also, we will get into a situation to change the code that uses the class components. Certain problems while writing React code via functional components may have already been solved via class components. If we know the class components, we will be able to solve the same problem quickly using functional components.

Knowing the class components is crucial if you are planning to be an amazing React developer.

We invite you to follow us on social networks so you can keep up with all our latest projects and news.

Welcome to Elephant Solutions blog!

Welcome to Elephant Solutions blog!

This is a welcome blog post with the purpose to introduce Elephant Solutions blog section to the world. The welcoming blog gives us a chance to express our creativity and to announce the content type for the future period.

Through the blog, we want to share with you the answers we came across during the work on certain projects to help others overcome similar problems.

First of all, let us introduce ourselves.

Elephant Solutions is a Software Development company with an innovative team of experienced IT professionals and graphic designers providing high-quality solutions in the field of Information Technology. We have a team of talented engineers with decades of experience in various multinational projects that assist our clients in improving their business processes.

We offer our clients comprehensive IT solutions that span all aspects of our customers’ IT/IS enterprise.

If you are interested in why “Elephant Solutions”?

  • Elephant – because an elephant is a symbol of strength, power and safeness.
  • Solutions – because we don’t offer services, but solutions.

Find out more in ABOUT US section

From now on we will have the practice of writing blogs on topics from the technology industry. This will be a place for anyone who has any interest in technology, anyone who is passionate about work in the IT field. The target group of the blog consists of software developers, designers, engineers, tech funs, entrepreneurs, consultants, project leaders, marketers. If you are one of them, follow us and get ready for the latest news from the IT industry.

We hope that our blog will be a place where people will come to read interesting, relevant, and thought-provoking content. Also, we’ll report, analyze, and provide perspective and recommendations from some of the industry’s leading minds. We will strive to provide blogs that impart important information, while also motivating, educating, and encouraging lively discussion. These are the types of blogs that Elephant Solutions team members prefer to read, and that’s exactly what we plan to provide.

As we continue to build the blog section, we’ll also create content related to breaking news and current events so our readers will always have access to timely information.

The idea is for the blog to be a place that will be the subject of your daily interest. Our blog will expand your knowledge, give you answers to your questions, solve some of the problems we all face, and acquaint you with the latest trends in software development.

Useful tips will also be one of the topics we will deal with. We will write about formal topics in the field of the IT industry related to application updates, as well as less formal topics related to communication with employees, business partners.

We invite you to follow us on social networks so you can keep up with all our latest projects and news.

Looking forward to growing with you as we embark on this new journey.

You’ll hear from us very soon!