Dung (Donny) Nguyen

Senior Software Engineer

State

In React.js, state is a built-in object that allows components to maintain and manage dynamic data. Unlike props, which are immutable and passed down from parent components, the state is managed within the component itself and can change over time, triggering a re-render of the component to reflect the updated data. Here’s a deeper look into the concept of state in React:

Key Characteristics of State

Using State in Functional Components

Functional components use the useState hook to manage state. Here’s an example:

import React, { useState } from 'react';

function Counter() {
  // Declare a state variable "count" with an initial value of 0
  const [count, setCount] = useState(0);

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

export default Counter;

In this example:

Using State in Class Components

Class components use the state property to manage state. Here’s an example:

import React, { Component } from 'react';

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

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>Click me</button>
      </div>
    );
  }
}

export default Counter;

In this example:

State vs. Props

Best Practices

State is crucial in React for building interactive and dynamic user interfaces. By managing state effectively, we can create responsive and intuitive applications.