Skip to main content

Archive

Show more

Props and State in React.js

Props and State in React.js

Props and state are fundamental concepts in React.js that allow components to manage data and interact with each other. Understanding props and state is essential for building dynamic and interactive user interfaces. Here's a comprehensive guide to props and state in React.js:


1. What are Props and State?

  • Props (Properties): Props are inputs that are passed into a component from its parent component. They are immutable and are used to customize the behavior and appearance of a component.
  • State: State represents the internal data of a component that can change over time. Unlike props, state is mutable and controlled by the component itself.

2. Props in React Components

Props are passed from parent components to child components as attributes. They allow data to be shared between components in a unidirectional flow.

Example:

import React from 'react';

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}!</h1>;
  }
}

3. State Management

State is managed internally by a component and can be accessed and modified using the this.setState() method. Changes to state trigger re-renders of the component, updating the UI accordingly.

Example:

import React from 'react';

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

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

4. Props vs. State

  • Props: Immutable, passed from parent components, used for configuring child components.
  • State: Mutable, managed internally by components, used for representing component-specific data.

5. Conclusion

Props and state are essential concepts in React.js for building dynamic and interactive user interfaces. By understanding how to effectively use props and state, developers can create reusable and maintainable components in React applications.

Comments