D Dev Notebook

React Components

React Components

What is Components?

React components are reusable and independent building blocks that define parts of a user interface. They let you split the UI into independent, reusable pieces that can be managed and developed separately.

A component is a JavaScript function or class that:

  • Returns a piece of JSX (JavaScript XML).
  • Represents part of the UI.
  • Can manage its own state and handle events.

Types of React Components

There are two main types of components in React:

a) Functional Components (modern & preferred)

function Notebook(){
    return(
        <>
            <h1>Hello, Welcome to Dev Notebook</h1>
        </>
    )
}

export default Notebook

Or using arrow functions:

const Welcome = () => <h1>Hello, world!</h1>;

b) Class Components (older way)

import React, { Component } from 'react';

class Welcome extends Component {
  render() {
    return <h1>Hello, world!</h1>;
  }
}

export default Welcome

Why Use Components?

  • Reusability: Build once, reuse everywhere.
  • Maintainability: Small components are easier to manage.
  • Separation of concerns: UI and logic stay organized.

Component with props

Props are used to receive data from parent components.

function AboutMe(props){
    return(
        <>
            <h1>Hello, my name is {props.username}</h1>
        </>
    )
}

export default AboutMe


// call the component
<AboutMe username="Nitin" />

Component with State

State is data that changes over time and affects what a component displays.

import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
}

export default Counter

On this page