DEV Community

Cover image for Getting Started with React and the Component Lifecycle
Neel Patel
Neel Patel

Posted on

Getting Started with React and the Component Lifecycle

So, you’ve heard all the buzz about React and want to see what it’s all about? You’re in the right place! Today, we’re going to go over the basics of React, and we’ll dive deep into the component lifecycle—the set of methods and hooks that let you control what your components do from birth to death (okay, maybe not that dramatic).

In this post, we’ll cover:

  1. What React is and why it’s so popular.
  2. Setting up your first React app.
  3. Understanding the Component Lifecycle with both Class Components and Hooks.
  4. Practical examples of how to use lifecycle methods and hooks.

Ready? Let’s React! ⚛️


What is React? 🤔

In a nutshell, React is a JavaScript library for building user interfaces. Created by Facebook, it lets you break down complex UIs into small, reusable pieces called components. React’s main claim to fame is its virtual DOM which makes updates to the UI super fast. This is what makes React ideal for building fast, responsive apps!

Why React?

  • Reusable Components: React components are like LEGO blocks for your app.
  • Fast UI Updates: The virtual DOM only updates what needs to be updated, keeping your app snappy.
  • Huge Ecosystem: React has tons of tools, libraries, and a massive community. Whatever you want to build, there’s probably a React package for it.

Setting Up Your First React App

Let’s get started by creating a new React app using Create React App (CRA), a super-easy way to bootstrap a new project.

Step 1: Install Node.js

Make sure you have Node.js installed. If not, you can download it from nodejs.org.

Step 2: Create Your App

Open up your terminal and run:

npx create-react-app my-first-react-app
Enter fullscreen mode Exit fullscreen mode

This will set up a new React project with everything you need. Once it’s done, navigate to your app directory and start the development server:

cd my-first-react-app
npm start
Enter fullscreen mode Exit fullscreen mode

Open up http://localhost:3000 in your browser, and boom! 🎉 You’ve got a React app running.


Understanding the Component Lifecycle

Now, let’s dig into the component lifecycle. This is basically the series of events that happen from when a component is mounted (added to the DOM), updated, and then unmounted (removed from the DOM).

Class Components and Lifecycle Methods

Back in the day (before hooks were a thing), React components were written as class components with special lifecycle methods to help control what the component does at each stage. Here’s a rundown of the main lifecycle methods:

  • componentDidMount: Runs after the component is added to the DOM. Perfect for API calls.
  • componentDidUpdate: Runs when the component updates (props or state changes).
  • componentWillUnmount: Runs right before the component is removed from the DOM. Great for cleanup (e.g., clearing timers).

Let’s see these in action with an example.

import React, { Component } from 'react';

class LifecycleDemo extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
    console.log("Constructor: Component is being created.");
  }

  componentDidMount() {
    console.log("ComponentDidMount: Component has mounted.");
  }

  componentDidUpdate(prevProps, prevState) {
    console.log("ComponentDidUpdate: Component has updated.");
  }

  componentWillUnmount() {
    console.log("ComponentWillUnmount: Component is about to be removed.");
  }

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

  render() {
    return (
      <div>
        <h1>Count: {this.state.count}</h1>
        <button onClick={this.increment}>Increment</button>
      </div>
    );
  }
}

export default LifecycleDemo;
Enter fullscreen mode Exit fullscreen mode

Here’s what’s happening:

  • Constructor: Initializes the state.
  • componentDidMount: Called once after the component mounts. Perfect for setting up anything that requires a DOM node.
  • componentDidUpdate: Called on updates (every time count changes).
  • componentWillUnmount: Called right before the component is destroyed. Great for cleanup.

Enter Hooks: Simplifying the Lifecycle

With the introduction of hooks in React, you can handle component lifecycle events in function components. Hooks are simpler, more intuitive, and remove the need for most lifecycle methods.

The useEffect Hook

The useEffect hook is the Swiss Army knife of lifecycle events. It lets you handle componentDidMount, componentDidUpdate, and componentWillUnmount all in one place.

Here’s how we’d recreate the LifecycleDemo component using useEffect:

import React, { useState, useEffect } from 'react';

function LifecycleDemo() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("Component has mounted.");

    return () => {
      console.log("Component will unmount.");
    };
  }, []); // Empty dependency array, so it only runs on mount/unmount

  useEffect(() => {
    console.log("Component has updated.");
  }, [count]); // Runs every time `count` changes

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

export default LifecycleDemo;
Enter fullscreen mode Exit fullscreen mode

Here’s what’s going on:

  • The first useEffect with an empty dependency array ([]) runs only once, like componentDidMount.
  • The second useEffect runs whenever count changes, similar to componentDidUpdate.
  • Inside the first useEffect, the return statement acts like componentWillUnmount, running cleanup code.

Hooks have definitely made handling lifecycle events in React easier and more flexible!


Practical Use Cases for Lifecycle Methods and Hooks

  1. API Calls: Use componentDidMount or useEffect to fetch data as soon as your component loads.
  2. Timers: Set up an interval or timeout in componentDidMount or useEffect, and clear it in componentWillUnmount or in the cleanup function inside useEffect.
  3. Event Listeners: Add listeners in componentDidMount or useEffect, and remove them in componentWillUnmount or the return cleanup function.

For example, setting up a timer looks like this with hooks:

useEffect(() => {
  const timer = setInterval(() => {
    console.log("Timer tick");
  }, 1000);

  return () => clearInterval(timer); // Clear the timer on unmount
}, []);
Enter fullscreen mode Exit fullscreen mode

Wrapping Up

React’s component lifecycle (with either class methods or hooks) gives you the power to manage what happens at each stage of a component’s life. Now that you’ve got a handle on the basics, go ahead and start building some UIs with React.

What lifecycle methods do you use the most? Drop a comment below and let me know how you use them, or share any tips you’ve picked up along the way. Happy coding! 😎

Top comments (0)