Understanding React Components

What are Components?

A Component in React is a reusable and independent piece of UI. They help in breaking the DOM into smaller, manageable parts.

Types of Components

Example - Functional Component

  function Greeting() {
    return <h1>Hello, React!</h1>;
  }
  

Example - Class Component

  class Greeting extends React.Component {
    render() {
      return <h1>Hello, React!</h1>;
    }
  }
  

Why Use Components?

When to Use?

Props in Components

Components receive data via props (short for properties):

  function Welcome(props) {
    return <h1>Hello, {props.name}</h1>;
  }

  <Welcome name="Kapil" />
  

State in Components

Components can also have their own state (data that changes over time):

  import { useState } from 'react';

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

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

Important Notes:

Use Cases

Conclusion

Components make building and maintaining large React applications easier by breaking the UI into small, independent pieces that can be composed together.