Functional Components
Functional Components explains modern React function components, JSX returns, props, state, Hooks, events, composition, exports, purity, accessibility, testing, and class-component differences.
Functional Components
Functional Components are the modern and standard way to create components in React.
A functional component is essentially a JavaScript function that returns React UI.
Learning Objectives
By the end of this lesson, you will understand:
- What a functional component is
- How to create one
- How React renders a functional component
- Component naming rules
- Returning JSX
- Using JavaScript inside components
- Passing props to functional components
- Using state inside functional components
- Handling events
- Composing functional components
- Exporting and importing components
- Common mistakes
- Functional vs class components
- Functional component best practices
What Is a Functional Component?
The simplest definition is:
A functional component is a JavaScript function that returns React UI.
Example:
function Welcome() {return <h1>Welcome to React</h1>;}
That's a functional component.
The important relationship is:
JavaScript Function↓Returns JSX↓React UI
Your First Functional Component
function Greeting() {return <h1>Hello, React!</h1>;}
Let's break it down:
function↓Greeting↓()↓{return JSX}
Greeting is the component.
Rendering the Component
Creating a component doesn't automatically display it.
You need to use it:
function Greeting() {return <h1>Hello, React!</h1>;}function App() {return (<div><Greeting /></div>);}
The flow is:
App↓Greeting↓<h1>Hello, React!</h1>
Component vs Function
Every functional component is a JavaScript function, but not every JavaScript function is a React component.
Regular function:
function add(a, b) {return a + b;}
Functional component:
function Header() {return <header>My Website</header>;}
The key difference is that the component participates in React's rendering model and returns UI.
Component Naming
Functional components should normally use PascalCase.
Correct:
function Header() {return <header>Header</header>;}
Correct:
function CourseCard() {return <div>Course</div>;}
Correct:
function UserProfile() {return <div>Profile</div>;}
Avoid:
function header() {}
and:
function courseCard() {}
Prefer:
HeaderCourseCardUserProfile
Why PascalCase?
React distinguishes component names from built-in HTML elements.
For example:
<div />
represents an HTML element.
Whereas:
<CourseCard />
represents a React component.
Capitalization provides this distinction.
Returning JSX
A functional component normally returns JSX.
function Welcome() {return (<section><h1>Welcome</h1><p>Learn React step by step.</p></section>);}
The JSX describes the UI React should render.
Parentheses and JSX
When JSX spans multiple lines, parentheses make the return easier to read:
function Header() {return (<header><h1>TechLearningPro</h1><nav>Navigation</nav></header>);}
You can also write:
function Header() {return <h1>Hello</h1>;}
Both are valid.
Functional Components Can Return HTML-Like JSX
For example:
function Profile() {return (<div><h2>Student Profile</h2><p>React Developer</p></div>);}
Remember:
JSX looks like HTML, but it is JavaScript syntax that describes UI.
Functional Components Can Contain JavaScript
This is an important feature.
function User() {const name = "Jagannath";return (<h1>Hello, {name}</h1>);}
The component contains:
JavaScript+JSX
Variables Inside Components
You can define variables:
function Course() {const title = "React Fundamentals";const price = 4999;return (<div><h2>{title}</h2><p>₹{price}</p></div>);}
The {} allows JavaScript expressions to be used inside JSX.
Expressions Inside JSX
For example:
function Course() {const price = 5000;const discount = 500;return (<p>Final price: ₹{price - discount}</p>);}
Result:
Final price: ₹4500
You can use JavaScript expressions inside JSX.
Functional Components Can Receive Props
Components can accept information from their parent.
function Greeting({ name }) {return <h1>Hello, {name}</h1>;}
Then:
<Greeting name="Jagannath" />
The component receives:
name↓Greeting↓Hello, Jagannath
Props will be covered in much greater detail separately.
Props Are Function Inputs
A useful mental model:
function Greeting({ name }) {return <h1>Hello, {name}</h1>;}
Think of it like:
Props↓Function↓UI
Similar to:
function greet(name) {return `Hello, ${name}`;}
This analogy is useful when learning React.
Multiple Props
A functional component can accept multiple props.
function CourseCard({title,instructor,price}) {return (<article><h2>{title}</h2><p>{instructor}</p><strong>₹{price}</strong></article>);}
Use it:
<CourseCardtitle="React"instructor="John"price={4999}/>
Functional Components Can Have State
Modern React allows functional components to use state through Hooks.
Example:
import { useState } from "react";function Counter() {const [count, setCount] = useState(0);return (<buttononClick={() => setCount(count + 1)}>Count: {count}</button>);}
The component now has its own state.
State Flow
The basic flow is:
Initial State↓Component Renders↓User Interaction↓State Update↓React Re-renders↓Updated UI
For the counter:
count = 0↓click↓count = 1↓UI updates
Functional Components and Hooks
Hooks allow functional components to use React features.
Common Hooks include:
useStateuseEffectuseContextuseReduceruseMemouseCallbackuseRef
We'll study each of these later.
The important point now is:
Functional components can use React Hooks.
Handling Events
Functional components can define event handlers.
function LoginButton() {function handleLogin() {console.log("Login clicked");}return (<button onClick={handleLogin}>Login</button>);}
Here:
User clicks button↓onClick↓handleLogin()
Event Handler With State
import { useState } from "react";function LikeButton() {const [liked, setLiked] = useState(false);function handleClick() {setLiked(!liked);}return (<button onClick={handleClick}>{liked ? "Liked" : "Like"}</button>);}
The component contains:
State+Event+Logic+UI
This is a very common React pattern.
Conditional Rendering
Functional components can conditionally render UI.
function UserStatus({ isLoggedIn }) {if (isLoggedIn) {return <h2>Welcome back!</h2>;}return <h2>Please log in.</h2>;}
Or:
function UserStatus({ isLoggedIn }) {return (<h2>{isLoggedIn? "Welcome back!": "Please log in."}</h2>);}
Rendering Lists
Functional components commonly render arrays.
function CourseList() {const courses = ["React","Java","Spring Boot"];return (<ul>{courses.map(course => (<li key={course}>{course}</li>))}</ul>);}
The component:
Data↓map()↓JSX↓UI
Functional Components Can Call Functions
For example:
function calculatePrice(price, discount) {return price - discount;}function Course() {const finalPrice =calculatePrice(5000, 500);return (<h2>₹{finalPrice}</h2>);}
Components are still JavaScript functions, so normal JavaScript concepts remain available.
Functional Components Can Compose Other Components
This is one of their most important capabilities.
function Header() {return <header>Header</header>;}function CourseList() {return <section>Courses</section>;}function Footer() {return <footer>Footer</footer>;}function App() {return (<><Header /><CourseList /><Footer /></>);}
Component tree:
App├── Header├── CourseList└── Footer
Functional Components Can Be Nested in the Tree
For example:
function CourseCard() {return <article>Course</article>;}function CourseList() {return (<section><CourseCard /><CourseCard /></section>);}function App() {return <CourseList />;}
Tree:
App↓CourseList├── CourseCard└── CourseCard
This is composition.
Separate Component Files
A professional project generally separates meaningful components.
src/│├── components/│ ├── Header.jsx│ ├── CourseCard.jsx│ └── Footer.jsx│├── App.jsx└── main.jsx
For example:
CourseCard.jsx
function CourseCard() {return (<article><h2>React Fundamentals</h2></article>);}export default CourseCard;
Then:
App.jsx
import CourseCard from "./components/CourseCard";function App() {return <CourseCard />;}export default App;
Default Export
You can export a component like this:
function Header() {return <header>Header</header>;}export default Header;
Then import:
import Header from "./Header";
Named Export
You can also use a named export:
export function Header() {return <header>Header</header>;}
Then:
import { Header } from "./Header";
Both are valid module patterns.
Arrow Function Components
Functional components can also be written as arrow functions.
const Welcome = () => {return <h1>Welcome</h1>;};
Or:
const Welcome = () => (<h1>Welcome</h1>);
Both represent functional components.
Traditional Function vs Arrow Function
Traditional:
function Welcome() {return <h1>Welcome</h1>;}
Arrow:
const Welcome = () => {return <h1>Welcome</h1>;};
Both are commonly used.
For beginners, the traditional function syntax can sometimes be easier to understand because it clearly communicates:
This is a function.
Which Syntax Should You Use?
There is no requirement that all React components must use arrow functions.
Both are valid:
function Header() {return <header />;}
and:
const Header = () => {return <header />;};
Choose a consistent style for your project.
Implicit Return
Arrow functions allow a shorter syntax:
const Header = () => (<header><h1>My Website</h1></header>);
Because the parentheses create an implicit return.
Equivalent:
const Header = () => {return (<header><h1>My Website</h1></header>);};
Functional Components and Purity
A good React component should generally behave predictably.
For the same inputs:
Props + State + Context↓Output
The rendering logic should avoid unexpected side effects.
For example, avoid doing this directly during rendering:
function User() {fetch("/api/user");return <h1>User</h1>;}
Network requests and other side effects need appropriate React patterns.
We'll study Effects separately.
Don't Perform Side Effects During Rendering
Rendering should primarily calculate UI.
Think:
Render↓Calculate UI↓Return JSX
Side effects such as:
Network requestsSubscriptionsTimersDOM manipulation
require appropriate handling.
This distinction becomes extremely important when learning useEffect.
Functional Components and this
One major advantage for modern React developers is that functional components don't use the class component this model.
You don't write:
this.statethis.setStatethis.props
Instead, functional components use:
propsuseStateuseContextother Hooks
This makes the programming model more function-oriented.
Functional Components vs Class Components
Historically, React applications commonly used class components.
Example:
class Counter extends React.Component {state = {count: 0};render() {return (<button>{this.state.count}</button>);}}
Modern React generally favors functional components.
Equivalent modern approach:
function Counter() {const [count, setCount] = useState(0);return (<button>{count}</button>);}
Why Functional Components Became Standard
Functional components became the preferred style because Hooks allow functions to use React features without class-specific concepts.
They generally provide:
Simpler syntaxHooksCompositionLess class boilerplateNo this bindingReusable logic through custom Hooks
Modern React development is centered around functional components and Hooks.
Functional Components and Custom Hooks
One of the most powerful modern patterns is extracting reusable logic into custom Hooks.
For example:
function useOnlineStatus() {// reusable state/effect logic}
Then:
function UserStatus() {const isOnline =useOnlineStatus();return (<p>{isOnline ? "Online" : "Offline"}</p>);}
This allows logic to be reused without duplicating component code.
We'll study custom Hooks later.
Functional Components and Composition
Suppose we have:
function Button({ children }) {return (<button>{children}</button>);}
Now:
function Login() {return (<Button>Login</Button>);}
The Button component doesn't need to know what the parent wants to put inside it.
This is a powerful form of composition.
Component Responsibilities
A functional component should ideally have a clear responsibility.
Good:
LoginFormCourseCardSearchBarNavigationUserProfile
Potentially problematic:
ApplicationEverythingComponent
If a component handles:
AuthenticationPaymentsCoursesNotificationsReportsSettings
it probably needs better decomposition.
Keep Components Understandable
Compare:
function CourseCard() {// 500 lines of logic// API calls// filtering// payment processing// authentication// UI}
with:
function CourseCard({title,instructor,price}) {return (<article><h2>{title}</h2><p>{instructor}</p><strong>₹{price}</strong></article>);}
The second component is much easier to understand.
Functional Components Don't Have to Be Tiny
Don't interpret "small components" as:
Every component must be only 10 lines.
A component can legitimately contain significant logic.
The real question is:
Does this component have a coherent responsibility?
That's more important than line count.
A Real Example
Let's create a product component:
function ProductCard({name,price,inStock}) {return (<article><h2>{name}</h2><p>Price: ₹{price}</p><p>{inStock? "In stock": "Out of stock"}</p></article>);}
Use it:
function App() {return (<><ProductCardname="Banarasi Saree"price={4999}inStock={true}/><ProductCardname="Silk Saree"price={6999}inStock={false}/></>);}
One component can represent many products.
Component Lifecycle Thinking
Even with functional components, a component has a lifecycle-like progression:
Component enters tree↓Render↓Updates↓Re-render↓Eventually removed
Hooks such as useEffect allow you to synchronize with external systems during appropriate phases.
We'll cover this in detail later.
Functional Components and Re-rendering
Consider:
function Counter() {const [count, setCount] =useState(0);return (<buttononClick={() =>setCount(count + 1)}>{count}</button>);}
When setCount updates state:
State changes↓React schedules an update↓Component renders again↓New UI description↓React updates necessary DOM
The function being called again does not mean React throws away the entire application.
Important: Rendering Is Not DOM Replacement
A beginner may think:
State change↓Delete entire page↓Create entire page again
That's not the right mental model.
Instead:
State change↓React renders↓React determines changes↓Necessary DOM updates
This distinction becomes important when studying React's rendering model.
Functional Components and Accessibility
Components should also produce accessible UI.
For example:
Good:
function SearchButton() {return (<button>Search</button>);}
Avoid replacing semantic HTML unnecessarily:
function SearchButton() {return (<div onClick={handleSearch}>Search</div>);}
A real <button> already provides important browser behavior and accessibility semantics.
Functional Components and Testing
Functional components are easy to test at the UI level.
For example:
function Greeting({ name }) {return <h1>Hello, {name}</h1>;}
A test can render:
name = "Jagannath"
and verify that:
Hello, Jagannath
appears.
Testing should generally focus on user-observable behavior rather than internal implementation details.
Common Mistake: Calling a Component Like a Normal Function
You might see:
function Greeting() {return <h1>Hello</h1>;}
and incorrectly write:
<div>{Greeting()}</div>
Although React components are functions, you generally use them as components:
<Greeting />
Why?
Because React needs to manage the component within its rendering model, including things such as Hooks and component identity.
Common Mistake: Calling Hooks Conditionally
Incorrect:
function User() {if (isLoggedIn) {const [name, setName] =useState("");}return <div />;}
Hooks must follow the Rules of Hooks.
Generally:
function User() {const [name, setName] =useState("");if (!isLoggedIn) {return <Login />;}return <Profile name={name} />;}
We'll study the Rules of Hooks in detail later.
Common Mistake: Mutating State Directly
Avoid:
user.name = "John";
when user is React state.
Instead, use the appropriate state update mechanism.
For example:
setUser({...user,name: "John"});
State management deserves a dedicated lesson.
Common Mistake: Side Effects During Render
Avoid:
function Component() {localStorage.setItem("key","value");return <div />;}
Rendering should remain predictable.
Side effects need appropriate handling.
Common Mistake: Giant Functional Components
Functional components can still become badly designed.
The fact that a component uses a function doesn't automatically make the architecture good.
Bad:
App.jsx└── 1500-line function
Functional programming syntax doesn't replace good architecture.
Common Mistake: Overusing Components
Don't create:
OneWordComponentOneIconComponentOneDivComponentOneSpanComponent
unless there is a meaningful reason.
Use components where they create:
ReuseClarityEncapsulationIndependent behaviorMeaningful abstraction
Functional Component Best Practices
1. Use clear names
function CourseCard() {}
2. Keep responsibilities focused.
3. Prefer explicit props.
<CourseCard title="React" />
4. Keep rendering predictable.
5. Avoid side effects during rendering.
6. Use Hooks according to their rules.
7. Compose components.
8. Extract reusable logic into custom Hooks when appropriate.
9. Prefer semantic HTML.
10. Don't optimize prematurely.
A Complete Example
Let's combine the concepts.
import { useState } from "react";function CourseCard({title,instructor,price}) {const [enrolled, setEnrolled] =useState(false);function handleEnroll() {setEnrolled(true);}return (<article><h2>{title}</h2><p>Instructor: {instructor}</p><p>Price: ₹{price}</p><buttononClick={handleEnroll}disabled={enrolled}>{enrolled? "Enrolled": "Enroll"}</button></article>);}
This single component demonstrates:
Functional component+Props+State+Event handling+Conditional rendering+JSX
Using the Component
function App() {return (<main><CourseCardtitle="React Fundamentals"instructor="John"price={4999}/><CourseCardtitle="Advanced React"instructor="Sarah"price={6999}/></main>);}
The same component is reused with different data.
The Complete Mental Model
Think of a functional component like this:
Functional Component│▼JavaScript Function│┌────────────────┼────────────────┐▼ ▼ ▼Props State Context│ │ │└────────────────┼────────────────┘▼Logic│▼JSX│▼React│▼UI
This is the foundation for everything that follows.
Functional Components vs Class Components
| Feature | Functional | Class |
|---|---|---|
| Syntax | Function | Class |
| Modern React | ✅ Preferred | ⚠️ Legacy/common in older code |
| Hooks | ✅ | ❌ |
this | Not required | Required |
| State | Hooks | this.state |
| Updates | State setters | setState() |
| Logic reuse | Custom Hooks | Patterns such as HOCs/render props |
| Modern development | Standard | Mostly legacy code |
If you're learning modern React today:
Focus primarily on functional components and Hooks.
You should still understand class components enough to maintain older React codebases.
Interview questions & answers
Interview preparation
5 questions grouped by difficulty — expand any card for a model answer and follow-up probe.
Beginner
1What Is a Functional Component?
BeginnerModel answer
A functional component is a JavaScript function that participates in React's component model and returns JSX describing the UI.
Modern functional components can use Hooks for state, effects, context, and other React capabilities.
They can receive data through props and compose other components.
2Can a Functional Component Have State?
BeginnerModel answer
Yes.
Functional components use Hooks such as useState for state.
Before Hooks, they were commonly used for simpler stateless UI; with Hooks, they can handle sophisticated stateful behavior.
3Is Every Function a React Component?
BeginnerModel answer
No.
A normal JavaScript function is not automatically a React component.
A functional component participates in React's rendering and component model and returns React-renderable UI.
Intermediate
4Why Are Functional Components Preferred?
IntermediateModel answer
Modern React favors functional components because Hooks provide access to React features without the complexity of class components and this.
Functional components also make it easier to reuse stateful logic through custom Hooks and compose UI in a straightforward way.
Advanced
5Function Component vs Function?
AdvancedModel answer
A functional component is implemented using a JavaScript function, but React uses it as part of the component tree.
It returns React-renderable UI and can use props, state, context, and Hooks.
A normal JavaScript function does not necessarily participate in React rendering.
Practical Exercise
Create this component:
StudentCard
It should accept:
namecourseprogress
Expected usage:
<StudentCardname="Rahul"course="React"progress={75}/>
Expected UI:
RahulReactProgress: 75%
Solution
function StudentCard({name,course,progress}) {return (<article><h2>{name}</h2><p>Course: {course}</p><p>Progress: {progress}%</p></article>);}
Slightly Advanced Exercise
Now add a button:
Mark Complete
When clicked, change:
Progress: 75%
to:
Progress: 100%
This introduces the next major concept:
Functional Component↓State↓Event↓State Update↓Re-render
The Most Important Mental Model
When you see:
function CourseCard({ title }) {return (<article><h2>{title}</h2></article>);}
Think:
CourseCard│▼JavaScript Function│▼Props│▼JSX│▼React renders│▼UI
And when state is added:
Props + State↓Functional Component↓JSX↓UI↑│User interaction│State update│setState()
That is the core model of modern React functional components.