What Is Functional Component in React: Simple Explanation and Example
functional component in React is a JavaScript function that returns UI elements using JSX. It is a simple and modern way to create components without using classes, focusing on rendering UI based on input props.How It Works
Think of a functional component as a small machine that takes some input and produces a visible part of a webpage. The input is called props, which are like instructions or ingredients you give to the machine. The machine then returns what should appear on the screen, usually written in JSX, which looks like HTML but works inside JavaScript.
Unlike older class components, functional components are just plain functions. They don’t have complicated internal states or lifecycle methods by default. Instead, they focus on showing UI based on the input they get. This makes them easier to understand and test, like a simple recipe that always produces the same dish when given the same ingredients.
Example
This example shows a functional component that greets a user by name. It receives a name prop and displays a greeting message.
import React from 'react'; function Greeting({ name }) { return <h1>Hello, {name}!</h1>; } export default function App() { return <Greeting name="Alice" />; }
When to Use
Use functional components whenever you want to create a piece of UI that depends on input data and does not require complex internal logic. They are perfect for buttons, headers, lists, or any part of the page that just shows information.
With React hooks, functional components can also handle state and side effects, making them suitable for almost all component needs in modern React apps. They are the recommended way to write components today because they are simpler and more efficient.
Key Points
- Functional components are simple JavaScript functions returning JSX.
- They receive
propsas input to customize their output. - Hooks allow functional components to manage state and side effects.
- They are easier to read, test, and maintain than class components.
- Functional components are the modern standard in React development.