Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 14, 2021 01:16 pm GMT

Learn React and Lifecycle Methods By Building Netflix

learn-react-by-building-netflix

I'm Hiep. I work as a full-time software engineer. Most of my open-source projects are focused on one thing - to help people learn .

Before moving on with this part, you should follow the first part in this series:

The first part - Learn React By Building Netflix:

The repository helps you learn lifecycle methods by buiding Netflix. It means that you are learning life cycle methods by building a real-life project. I will explain concepts in detail. This post is the seventh part in my series and it is suitable for beginners.

If you feel the repository is useful, please help me share the post and give me a . It will make me feel motivation to work even harder. I will try to make many open sources and share to the community.

I also created some series that help you improve your practical skills:

1. Master Design Patterns by Building Real Projects - Javascript.

Github: https://github.com/hieptl/master-javascript-design-patterns-by-building-real-projects

Blog: https://dev.to/hieptl/series/13039

Preface

This course will help you to learn lifecycle methods by building Netflix. It means that you are learning by doing a real-life project. You will understand about different phases such as mounting, updating and unmounting.

If you are using function components, you do not need to care about lifecyle methods. Because from React v16.8, we have supporting from React Hooks. I will have another post to explain about React Hooks by Building Netflix.

Table of Contents

Table of Images.

0. How to Run the Project.

  • Step 1: Clone the project by using git clone or download the zip file.

  • Step 2: Open "terminal" / "cmd" / "gitbash" and change directory to "netflix-clone" and run "npm install" to install dependencies.

  • Step 3: Run "npm run start" to run the fron-end project.

1. Live Demo.

2. Introduction about the Creator.

2.1. Greenwich University.

  • Valedictorian.

  • GPA 4.0 / 4.0.

  • Machine Learning paper - Recommendation System - IEEE/ICACT2020.

  • Co-Founder / Mentor IT club.

2.2. Hitachi Vantara Vietnam.

  • Employee of the year.

  • Second prize - innovation contest.

  • Techlead - HN branch.

  • One of CoE Leaders (Center of Excellence).

3. Prequisites.

3.1. Softwares.

  • Install NodeJS.

  • An IDE or a text editor (VSCode, Intellij, Webstorm, etc).

3.2. Technical Skills.

  • Basic programming skill.

  • Basic HTML, CSS, JS skills.

3.3. Materials.

  • Html, css, js (source code) was prepared because I want to focus on React and share knowledge about React. Building html and css from scratch would take a lot of time.

  • README.md (the md file will contain everything about the course).

  • Netflix data will be used to import to Firebase. In this course, we use Firebase as our back-end service.

4. Purposes of the Course.

4.1. Final Project.

  • The course would help you have understanding about React.

  • You could build the final project with end-to-end solution (front-end solution using React and back-end solution using Firebase).

4.2. Job.

  • After finishing the course, you could get a job with fresher / junior position.

5. React Lifecycle Methods.

5.1. What.

  • We have two ways in order to define React's components (class component or function component).

  • If we are using class components, we need to understand about different phases in component's lifecycle.

  • For this reason, we can know the purpose of each lifecycle's method and write code in the correct places and avoid unexpected behaviour.

5.3. Why

  • We need to find the correc place to write code and avoid issues.

For example: we should not write code to fetch apis inside the render function. We should write it in the componentDidMount and so on.

5.4. When

  • If you are using class component in your applications, you should have understanding about lifecyle methods.

5.5. How

  • Define your components as class components.

  • Write lifecycle methods for different phases of your components

6. Scenarios.


reduc-middleware-architecture

Figure 1. Detail Page - Netflix.

In the previous posts, we defined Detail component as a function component. However, as mentioned above, we can write lifeycle methods if our components are class components. For this reason, we should refactor our Detail component to class component in order to learn about lifecyle methods in React.

Step 1: Update Home.js with the following code.

...{/* Detail */}<Detail movie={selectedMovie} onDetailClosed={closeDetail} />{/* End Detail */}...

1st NOTE:

  • In the previous post, we use conditonal rendering in React to show / hide the Detail component based on selectedMovie state.

  • However, in this post, we will let the Detail component be available from the beginning to learn about lifecycle methods.

  • We will write the logic to show / hide the UI inside the Detail component.

Step 3: Convert Detail component to class component.

import React from "react";/** * create Detail component * @param {*} props which are passed to Detail component. */class Detail extends React.Component {  constructor(props) {    super(props);    console.log("constructor was called");    this.state = {};  }  static getDerivedStateFromProps(props, state) {    console.log("getDerivedStateFromProps was called");    return state;  }  shouldComponentUpdate() {    console.log("shouldComponentUpdate was called");    return true;  }  render() {    console.log("render was called");    const { movie, onDetailClosed } = this.props;    if (!movie) {      return null;    }    // return detail elements.    return (      <div className="detail">        {/* Detail Banner Image */}        <div          className="detail__image"          style={{            backgroundImage: `url(https://image.tmdb.org/t/p/original/${movie?.backdrop_path})`          }}        >          <span className="detail__title">{movie?.original_name}</span>        </div>        {/* End Detail Banner Image */}        {/* Detail Fade Bottom Animation */}        <div className="banner--fadeBottom detail__fade-image"></div>        {/* End Detail Fade Bottom Animation */}        {/* Detail Actions */}        <div className="detail__actions">          <button className="detail__btn mgr-8">Play</button>          <button className="detail__btn" onClick={onDetailClosed}>            Back          </button>        </div>        <div className="detail__description">          <div className="detail__description-title">Description</div>          <p className="detail__description-content">{movie?.overview}</p>        </div>        {/* End Detail Actions */}      </div>    );  }  componentDidMount() {    console.log("componentDidMount was called");  }  getSnapshotBeforeUpdate(prevProps, prevState) {    console.log("getSnapshotBeforeUpdate was called");    return prevState;  }  componentDidUpdate() {    console.log("componentDidUpdate was called");  }  componentWillUnmount() {    console.log("componentWillUnmount was called");  }}export default Detail;

2nd NOTE:

  • It is time to talk about some new methods in the Detail component.

  • In fact, we have three phases in the lifecycle: mounting, updating, unmounting.

3rd NOTE:

  • In the mounting phase, we have constructor, getDerivedStateFromProps, render and componentDidUpdate. If you run the code and check the console for the first time. We will see the following result:
constructor was calledgetDerivedStateFromProps was calledrender was calledcomponentDidMount was called
  • They will be executed in order.

  • constructor is used to initial state in our application. If you pass props as parameter and pass to super, you can access props in your component by writing this.props.propName.

  • getDerivedStateFromProps: Invoked right before calling render() and is invoked on every render. This exists for rare use cases where you need derived state.

  • render: is used to render React elements.

  • componentDidMount: Executed after first rendering and where all AJAX requests, DOM or state updates, and set up event listeners should occur.

4th NOTE:

  • After the component was rendered, we can check the methods of the updating phase by selecting a movie. The updating phase will contain getDerivedStateFromProps, shouldComponentUpdate, render, getSnapshowBeforeUpdate, componentDidUpdate.

  • If you check the console, you will see the following result:

getDerivedStateFromProps was calledshouldComponentUpdate was calledrender was calledgetSnapshotBeforeUpdate was calledcomponentDidUpdate was called
  • getDerivedStateFromProps and render will take part in both phases (mounting and unmounting).

  • shouldComponentUpdate: Determines if the component will be updated or not. By default it returns true. If you are sure that the component doesn't need to render after state or props are updated, you can return false value. It is a great place to improve performance as it allows you to prevent a re-render if component receives new prop.

  • getSnapshotBeforeUpdate: Executed right before rendered output is committed to the DOM. Any value returned by this will be passed into componentDidUpdate(). This is useful to capture information from the DOM i.e. scroll position.

  • componentDidUpdate: Mostly it is used to update the DOM in response to prop or state changes. This will not fire if shouldComponentUpdate() returns false.

5th NOTE:

  • If you destroy the component, we can see the unmounting phase. componentWillUnmount will be executed.

  • componentWillUnmount It will be used to cancel any outgoing network requests, or remove all event listeners associated with the component. You will see the result:

componentWillUnmount was called

Summary

  • We have three phases in the lifecycle: mounting, __updating, and unmounting.

  • In the mounting phase, we have constructor, getDerivedStateFromProps, render and componentDidUpdate.

  • The updating phase will contain getDerivedStateFromProps, shouldComponentUpdate, render, getSnapshowBeforeUpdate, componentDidUpdate.

  • The unmounting phase will contain componentWillUnmount.

Thank you so much for taking the course. I hope that you could understand about React lifecycle methods and you can build many real-life projects by using React (as front-end) and Firebase (as back-end) in order to solve many problems and make our life become better.

Useful Resources to Learn React.

[1]. https://reactjs.org/docs/getting-started.html.

References

[1]. https://reactjs.org/docs/getting-started.html.
[2]. https://firebase.google.com/docs/database.
[3]. https://firebase.google.com/docs/auth/web/password-auth.
[4]. https://firebase.google.com/docs/hosting.


Original Link: https://dev.to/hieptl/learn-react-and-lifecycle-methods-by-building-netflix-4683

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To