React.js / React Basics

Managing State and Lifecycle Methods

In this tutorial, we will learn about two important concepts in React - State and Lifecycle methods. State allows us to create and manage component data, and lifecycle methods let…

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Covers the fundamental concepts of React.js, including JSX, components, and state management.

1. Introduction

Goal

This tutorial aims to provide a deep understanding of managing State and Lifecycle methods in React.

Learning Outcomes

By the end of this tutorial, you will be able to:
- Understand the concept of State in React and how to use it
- Understand React's Lifecycle methods and how to use them
- Know how to manage State and use Lifecycle methods in your React applications

Prerequisites

  • Basic understanding of JavaScript
  • Familiarity with React components

2. Step-by-Step Guide

State in React is a built-in object that stores component data. It is mutable and can be accessed and updated throughout the component.

Lifecycle methods are special methods provided by React that allow us to run code at particular times in the process of a component's life cycle.

State

State is managed within the component (local state).

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    // state is initialized
    this.state = {
      name: 'John',
    };
  }
}

Here, name is a state variable initialized with the value 'John'.

Lifecycle Methods

Lifecycle methods are categorized into three parts: Mounting, Updating, and Unmounting.

Mounting

These methods are called in the following order when an instance of a component is being created and inserted into the DOM:
- constructor()
- static getDerivedStateFromProps()
- render()
- componentDidMount()

Updating

An update can be caused by changes to props or state. These methods are called in this order when a component is being re-rendered:
- static getDerivedStateFromProps()
- shouldComponentUpdate()
- render()
- getSnapshotBeforeUpdate()
- componentDidUpdate()

Unmounting

This method is called when a component is being removed from the DOM:
- componentWillUnmount()

3. Code Examples

Example 1: Managing State

Here's an example of a simple counter application where state is used.

class Counter extends React.Component {
  constructor(props) {
    super(props);
    // Initializing state
    this.state = { count: 0 };
  }

  incrementCount = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={this.incrementCount}>Click Me</button>
      </div>
    );
  }
}

Here, count is a state variable. The incrementCount method updates the state. The render method renders the state to the DOM.

Example 2: Lifecycle Methods

Here's an example of a component using lifecycle methods.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    console.log('Constructor');
  }

  componentDidMount() {
    console.log('componentDidMount');
  }

  componentDidUpdate() {
    console.log('componentDidUpdate');
  }

  componentWillUnmount() {
    console.log('componentWillUnmount');
  }

  render() {
    console.log('Render');
    return <div>My Component</div>;
  }
}

In the console, you'll see logs for each lifecycle method as they get executed in order.

4. Summary

  • State is a mutable object that stores component data.
  • Lifecycle methods allow us to run code at specific points in a component's life cycle.

Next steps for learning would be understanding props in React, and how to pass data between components.

5. Practice Exercises

  1. Create a React component with a state variable color initialized as 'red'. Add a button that changes the state's color to 'blue'.

  2. Create a React component that logs a message to the console in each lifecycle method.

  3. Create a counter application where the counter value resets to zero after reaching 10. Implement this using state and lifecycle methods.

Here are the solutions for each exercise:

class ColorComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { color: 'red' };
  }

  changeColor = () => {
    this.setState({ color: 'blue' });
  };

  render() {
    return (
      <div>
        <p>The color is {this.state.color}</p>
        <button onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}
class LifecycleComponent extends React.Component {
  constructor(props) {
    super(props);
    console.log('Constructor');
  }

  componentDidMount() {
    console.log('componentDidMount');
  }

  componentDidUpdate() {
    console.log('componentDidUpdate');
  }

  componentWillUnmount() {
    console.log('componentWillUnmount');
  }

  render() {
    console.log('Render');
    return <div>Lifecycle Component</div>;
  }
}
class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  componentDidUpdate() {
    if (this.state.count > 10) {
      this.setState({ count: 0 });
    }
  }

  incrementCount = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={this.incrementCount}>Click Me</button>
      </div>
    );
  }
}

Keep practicing and exploring more about React!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

Backlink Checker

Analyze and validate backlinks.

Use tool

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

Random Number Generator

Generate random numbers between specified ranges.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help