DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Using Custom React Hooks to Simplify Complex Scenarios
  • Unleashing the Power of React Hooks
  • In-Depth Guide to Using useMemo() Hook in React
  • Build Your Own Shopping Cart With React Hooks

Trending

  • Automatic Code Transformation With OpenRewrite
  • Is Agile Right for Every Project? When To Use It and When To Avoid It
  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • Testing SingleStore's MCP Server
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. React Lifecycle Hooks, Part 1

React Lifecycle Hooks, Part 1

In this post, we go over the basics of lifecycle hooks in React and demonstrate how to use them in your JavaScript code.

By 
Souradip Panja user avatar
Souradip Panja
·
May. 22, 19 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
15.2K Views

Join the DZone community and get the full member experience.

Join For Free

I am basically Dotnet and Angular developer but recently I have done a project in React.js. Based on what I experienced I am going to share my knowledge on React lifecycle hooks.

In React a component will have four stages. React Component Stages

  1. Initialization

  2. Mouning 

  3. Updating

  4. Unmounting

Lifecycle hooks generally mean the flow of data or the loading of data, rendering of data or pages, and the triggering of any methods or events in a component

Initilization

Here we define the initial and default values for the props and states. The two methods in this phase are:

  •  getDefaultProps()
  • getInitialState() 
  • The  getInitialState method enables us to set the initial state value that is accessible inside the component via this.state.

    getDefaultProps can be used to define any default props which can be accessed via this.props.

    Each component in React contains several lifecycle methods that one can override to run code at particular times within the lifecycle. The methods that contain the word ‘will’ are called before an event happens while the methods that contain the word ‘did’ happen after an event.

    Mounting

    When the component is initially rendered and inserted into the DOM, the mounting methods are called. During mounting no update occurs. The methods used during mounting are called in this order:

    • constructor(): This method is called before the component is rendered and generally used to assign the default state value. We can also bind methods of the component with the ‘this’ keyword.

    • componentWillMount(): the method will be called before rendering HTML in the DOM. Generally API fetching is done in this hook. You can compare thengOnInit hook of Angular with this.

    • render(): In this method the HTML will be rendered.

    • componentDidMount(): After loading the data into the DOM this method will be called. React recommends using the setState method in this lifecycle hook.

    Another way you can check which is renderd first is to try to access a DOM property and try to change it’s color. In componentWillMount(), it will throw an error at that time the render method is not called, hence the DOM is not created. But in the componentDidMount() method it will work fine.

    import React, { Component } from 'react';  
    import { render } from 'react-dom';  
    import './style.css';  
      
    class App extends Component {  
      constructor() {  
        super();  
        this.state = {  
          name: 'React'  
        };  
      }  
      
      componentWillMount(){  
        console.log("Before rendering html");  
      //document.getElementById('test').style.color = 'red';  //this will give error
    
      
      }  
      
      componentDidMount(){  
          console.log("After rendering html");  
          document.getElementById('test').style.color = 'red';  
      }  
      
      render() {  
        return (  
          <div>  
              
            <p id="test">  
              Start editing to see some magic happen :)  
            </p>  
          </div>  
        );  
      }  
    }  
      
    render(<App />, document.getElementById('root'));  
    Hook React (JavaScript library)

    Opinions expressed by DZone contributors are their own.

    Related

    • Using Custom React Hooks to Simplify Complex Scenarios
    • Unleashing the Power of React Hooks
    • In-Depth Guide to Using useMemo() Hook in React
    • Build Your Own Shopping Cart With React Hooks

    Partner Resources

    ×

    Comments
    Oops! Something Went Wrong

    The likes didn't load as expected. Please refresh the page and try again.

    ABOUT US

    • About DZone
    • Support and feedback
    • Community research
    • Sitemap

    ADVERTISE

    • Advertise with DZone

    CONTRIBUTE ON DZONE

    • Article Submission Guidelines
    • Become a Contributor
    • Core Program
    • Visit the Writers' Zone

    LEGAL

    • Terms of Service
    • Privacy Policy

    CONTACT US

    • 3343 Perimeter Hill Drive
    • Suite 100
    • Nashville, TN 37211
    • support@dzone.com

    Let's be friends:

    Likes
    There are no likes...yet! 👀
    Be the first to like this post!
    It looks like you're not logged in.
    Sign in to see who liked this post!