fbpx

React State and Lifecycle

In React, state and lifecycle methods are crucial concepts that allow components to manage and respond to changes in data over time. Let’s explore React state and lifecycle in more detail:

React State:

State is a built-in object in React components that represents the mutable data managed by a component. When the state of a component changes, React re-renders the component, reflecting the updated state in the UI.

Class Component with State:

import React, { Component } from 'react';

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

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

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

export default Counter;

Functional Component with State (using Hooks):

import React, { useState } from 'react';

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

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

export default Counter;

React Lifecycle:

React components go through various lifecycle phases, and each phase provides opportunities to perform specific actions. Class components have lifecycle methods that can be overridden to execute code at certain points in the component’s life.

Mounting Phase:

  • constructor: Called when the component is being initialized.
  • render: Returns the JSX to be rendered.
  • componentDidMount: Called after the component has been rendered to the DOM.

Updating Phase:

  • render: Re-renders the component when state or props change.
  • componentDidUpdate: Called after the component has been updated.

Unmounting Phase:

  • componentWillUnmount: Called before the component is removed from the DOM.

Example of Lifecycle Methods in a Class Component:

import React, { Component } from 'react';

class LifecycleExample extends Component {
  constructor(props) {
    super(props);
    this.state = {
      message: 'Hello',
    };
    console.log('Constructor called');
  }

  componentDidMount() {
    console.log('Component did mount');
  }

  componentDidUpdate(prevProps, prevState) {
    console.log('Component did update');
  }

  componentWillUnmount() {
    console.log('Component will unmount');
  }

  updateMessage = () => {
    this.setState({ message: 'Updated Message' });
  };

  render() {
    console.log('Render called');
    return (
      <div>
        <p>{this.state.message}</p>
        <button onClick={this.updateMessage}>Update Message</button>
      </div>
    );
  }
}

export default LifecycleExample;

Example of useEffect Hook in a Functional Component:

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

function LifecycleExample() {
  const [message, setMessage] = useState('Hello');

  useEffect(() => {
    console.log('Component did mount');

    return () => {
      console.log('Component will unmount');
    };
  }, []);

  useEffect(() => {
    console.log('Component did update');
  }, [message]);

  const updateMessage = () => {
    setMessage('Updated Message');
  };

  console.log('Render called');

  return (
    <div>
      <p>{message}</p>
      <button onClick={updateMessage}>Update Message</button>
    </div>
  );
}

export default LifecycleExample;

Conclusion:

Understanding React state and lifecycle methods is essential for building dynamic and responsive React applications. State allows components to manage and update data, while lifecycle methods provide hooks to perform actions at specific points in a component’s life. As you become more familiar with React development, you’ll find these concepts fundamental for creating complex and interactive user interfaces.