What Are React Components?

React components are the building blocks of any React application. They encapsulate the UI and behavior of an element and can be reused throughout the app.


Types of React Components

  • Functional Components: Simple JavaScript functions that return JSX.
  • Class Components: ES6 classes that extend React.Component and include a render method.

1. Functional Components

Functional components are the most common type of components in modern React applications. They are simple and allow the use of hooks.

App.js

</>
Copy
import React from 'react';

function App() {
  return (
    <h2>Hello World</h2>
  );
}

export default App;

Output

Example for Functional React Components

2. Class Components

Class components were the traditional way of creating components before hooks were introduced. They allow you to use lifecycle methods and state.

App.js

</>
Copy
import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <h2>Hello World 2</h2>
    );
  }
}

export default App;

Output

Example for Class React Components

Props in Components

Props (short for “properties”) are used to pass data from one component to another. They are immutable and allow components to be dynamic.

App.js

</>
Copy
import React from 'react';

function Greeting(props) {
  return <h2>Hello, {props.name}!</h2>;
}

function App() {
  return (
    <div>
      <Greeting name="Arjun" />
      <Greeting name="Ram" />
    </div>
  );
}

export default App;

Output

Example for Using Props in Components

State in Class Components

State is an object that holds dynamic data within a class component. It is mutable and can be updated using setState.

App.js

</>
Copy
import React, { Component } from 'react';

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

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

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

export default App;

Output


Hooks in Functional Components

Hooks allow functional components to use state and lifecycle methods. The most common hooks are useState and useEffect.

App.js

</>
Copy
import React, { useState } from 'react';

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

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

export default App;

Output


Conclusion

React components are essential for building modular and reusable UI. Functional components with hooks are now the preferred approach due to their simplicity and power.