</>
Skip to content
React lessons (9/47)

React — Function Components

Basic Function Component

function Welcome() {
    return <h1>Hello, World!</h1>;
}

// Arrow function
const Welcome = () => {
    return <h1>Hello, World!</h1>;
};

// With implicit return
const Welcome = () => <h1>Hello, World!</h1>;

Function Component with Props

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

// Usage
<Welcome name="John" />

Function Component with State

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>
    );
}

Function Component Examples

// User profile component
function UserProfile({ user }) {
    return (
        <div className="profile">
            <img src={user.avatar} alt={user.name} />
            <h3>{user.name}</h3>
            <p>{user.email}</p>
        </div>
    );
}

// Todo item component
function TodoItem({ todo, onToggle, onDelete }) {
    return (
        <li className={todo.completed ? 'completed' : ''}>
            <span onClick={() => onToggle(todo.id)}>
                {todo.text}
            </span>
            <button onClick={() => onDelete(todo.id)}>
                Delete
            </button>
        </li>
    );
}

// Button component
function Button({ children, onClick, variant = 'primary' }) {
    return (
        <button
            className={`btn btn-${variant}`}
            onClick={onClick}
        >
            {children}
        </button>
    );
}

// Usage
function App() {
    return (
        <div>
            <Button onClick={() => alert('Clicked!')}>
                Click Me
            </Button>
        </div>
    );
}

Mini Practice

Write React code that:

  1. Creates a function component
  2. Uses props in a function component
  3. Adds state with useState hook
  4. Creates reusable components

Up Next

Next: Learn about Props.

Related Topics

Frequently Asked Questions about Function Components

What is Function Components in React?

Function Components is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Function Components?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Function Components.

Why is Function Components important in React?

Function Components is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.