[go: up one dir, main page]

DEV Community

Haque.
Haque.

Posted on

Day 5: State and Lifecycle Methods - ReactJS

Welcome to Day 5 of the "30 Days of ReactJS" challenge! Today, we’re going to explore two fundamental concepts in React: State and Lifecycle Methods. Understanding these will empower you to create dynamic, interactive applications.

What is State?

State in React refers to a built-in object that holds information that may change over the lifetime of a component. Unlike props, which are read-only and passed down from a parent component, state is local to the component and can be modified internally.

Think of state like a chalkboard. You can write and erase information on it as needed, allowing your component to adapt to changes, such as user input or data fetching.

Example: A Counter Component

Let's create a simple counter component that increases its count when a button is clicked:

import { useState } from 'react';

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button  => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Here, useState is a React hook that allows you to add state to a functional component. The count variable holds the current state, and setCount is the function to update it.

What Are Lifecycle Methods?

Lifecycle methods are special methods in React class components that allow you to run code at specific points in a component's lifecycle. This lifecycle includes mounting (adding to the DOM), updating (re-rendering), and unmounting (removal from the DOM).

Although class components are becoming less common with the introduction of React hooks, understanding lifecycle methods is still important, especially when working with older codebases.

Example: componentDidMount

A common lifecycle method is componentDidMount, which runs after the component is first rendered. It's often used for initializing data, such as fetching data from an API:

class DataFetcher extends React.Component {
  state = { data: null };

  componentDidMount() {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => this.setState({ data }));
  }

  render() {
    return (
      <div>
        {this.state.data ? (
          <p>Data: {this.state.data}</p>
        ) : (
          <p>Loading...</p>
        )}
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

In this example, componentDidMount fetches data as soon as the component is added to the DOM, and the state is updated with the fetched data.

Real-Life Example: A Restaurant Order
Imagine placing an order at a restaurant (component mounting). The kitchen starts preparing your food after you place the order (componentDidMount). As the food is being prepared (updating), you might get status updates. Finally, the food is served and you finish your meal (component unmounting).

State and Lifecycle with Vite

Since we’re using Vite for our development environment, setting up state and lifecycle methods is seamless. Vite’s fast development server ensures that your state changes and lifecycle methods are reflected almost instantly during development.

Here’s how you can structure your project to include state and lifecycle methods:

  1. Initialize State: Use useState in your functional components to manage dynamic data.
  2. Class Components for Lifecycle: If you’re using class components, implement lifecycle methods like componentDidMount and componentWillUnmount to manage side effects.

Wrapping Up

State and lifecycle methods are crucial for creating dynamic, responsive React applications. State allows your components to be interactive, while lifecycle methods give you control over how and when your components interact with the DOM.

Tomorrow, we’ll explore Handling Events in React, which will further enhance the interactivity of your applications.

Top comments (0)