Functional components let you create parts of a webpage using simple JavaScript functions. They make building user interfaces easy and clear.
0
0
Functional components in React
Introduction
When you want to create a simple UI part that shows some content.
When you need a reusable piece of UI that can accept data and display it.
When you want to use React hooks to add state or side effects.
When you want your code to be easy to read and maintain.
When you want to build modern React apps without using classes.
Syntax
React
function ComponentName(props) { return ( <div> {/* UI elements here */} </div> ); }
The function name should start with a capital letter.
It returns JSX, which looks like HTML but is JavaScript.
Examples
A simple component that shows a greeting message.
React
function Greeting() { return <h1>Hello, friend!</h1>; }
This component uses a prop to show a personalized welcome.
React
function Welcome(props) { return <h2>Welcome, {props.name}!</h2>; }
A functional component using a hook to add state and update the UI.
React
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Add 1</button> </div> ); }
Sample Program
This component shows how to track button clicks using state in a functional component. It updates the number each time you click the button.
React
import React, { useState } from 'react'; function ClickTracker() { const [clicks, setClicks] = useState(0); return ( <main> <h1>Click Tracker</h1> <p>You clicked {clicks} times.</p> <button onClick={() => setClicks(clicks + 1)} aria-label="Add one click">Click me</button> </main> ); } export default ClickTracker;
OutputSuccess
Important Notes
Always start component names with a capital letter to help React recognize them.
Use hooks like useState to add state inside functional components.
Functional components are easier to test and reuse than class components.
Summary
Functional components are simple JavaScript functions that return UI.
They can accept data through props and use hooks for state and effects.
They are the modern, recommended way to build React components.