Functional Components in React JS – Detailed Notes
Topic: Functional Components
Technology: React JS
Level: Beginner to Intermediate
Learning Objectives: Understand functional components, learn their syntax, create and reuse components, pass props, manage state with Hooks, handle events, render lists, and follow best practices.
React JS Training Course: JustAcademy React JS Training Course
Course Demo: Register for React JS Course Demo
1. What Are Functional Components in React?
Functional components are JavaScript functions that return React elements describing the user interface (UI). They are one of the most commonly used ways to build components in modern React applications.
A functional component can display text, images, buttons, forms, lists, and other components. It can also receive data through props and use React Hooks to manage state, access context, and synchronize with external systems.
Example
function Welcome() {
return (
<h1>Welcome to React JS!</h1>
);
}
export default Welcome;
Explanation:
function Welcome() declares a JavaScript function named Welcome.
return specifies the UI that the component describes.
is JSX representing a heading element.
export default Welcome makes the component available to other modules.
When React renders Welcome, it displays the heading defined by the component.
2. Why Are Functional Components Important?
Functional components make it possible to divide an application into small, reusable pieces. Instead of writing an entire application in one large component, developers can create separate components for different UI elements and features.
Advantages of functional components
- Simple syntax: They use standard JavaScript function syntax.
- Reusability: A component can be rendered multiple times.
- Props support: Components can receive data from parent components.
- State management: Hooks such as
useState allow components to manage changing data.
- Lifecycle-related behavior: Hooks such as
useEffect can synchronize with external systems.
- Maintainability: Small components are easier to update and understand.
- Testing: Component behavior can be tested independently.
- Composition: Multiple components can be combined to build complete interfaces.
3. Basic Syntax of a Functional Component
A functional component is declared using a JavaScript function. Its name should begin with an uppercase letter, and it usually returns JSX.
General syntax
function ComponentName() {
return (
<div>
{/* JSX content goes here */}
</div>
);
}
export default ComponentName;
Example: Greeting component
function Greeting() {
return (
<div>
<h2>Hello, Student!</h2>
<p>Welcome to the React course.</p>
</div>
);
}
export default Greeting;
Important points
- Use PascalCase for component names, such as
Greeting and UserProfile.
- Return valid React content, often written using JSX.
- Use a parent element or a Fragment when returning multiple sibling elements.
- Export the component if it needs to be imported into another file.
- Keep components focused on a clear purpose.
4. How to Create a Functional Component
Follow these steps to create and use a functional component in a React application.
Step 1: Create a component file
Create a file named Welcome.jsx inside the src folder or a suitable components folder.
Step 2: Define the component
function Welcome() {
return (
<h1>Welcome to My Application</h1>
);
}
export default Welcome;
Step 3: Import the component
In App.jsx, import the component using its file path.
import Welcome from "./Welcome";
function App() {
return (
<div>
<Welcome />
</div>
);
}
export default App;
Step 4: Render the application
In a typical React application created with a modern build tool, the entry file mounts the root component using React DOM.
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
createRoot(document.getElementById("root")).render(
<StrictMode>
<App />
</StrictMode>
);
Result: The application displays “Welcome to My Application” in the browser, assuming the project contains the expected HTML root element and file structure.
5. Using Arrow Functions for Functional Components
Functional components can also be written using arrow function syntax. Arrow functions are an alternative way to define JavaScript functions.
Using a regular function
function Message() {
return <p>Hello from React!</p>;
}
Using an arrow function
const Message = () => {
return <p>Hello from React!</p>;
};
export default Message;
Arrow function with an implicit return
const Message = () => (
<p>Hello from React!</p>
);
export default Message;
When the arrow function contains only a single expression to return, parentheses can be used for an implicit return. If you use curly braces for the function body, you generally need an explicit return statement.
| Feature |
Regular function |
Arrow function |
| Syntax |
function Message() { ... } |
const Message = () => { ... } |
| Return value |
Usually uses return |
Can use explicit or implicit return |
| Component usage |
Supported |
Supported |
| Recommendation |
Choose based on readability and project conventions |
Choose based on readability and project conventions |
6. Using JSX Inside Functional Components
JSX is a syntax extension that lets developers write HTML-like markup inside JavaScript. Functional components commonly use JSX to describe the UI they return.
Example
function Profile() {
const name = "Priya";
const course = "React JS";
return (
<section>
<h2>Student Profile</h2>
<p>Name: {name}</p>
<p>Course: {course}</p>
</section>
);
}
export default Profile;
Curly braces allow JavaScript expressions, such as variables and calculations, to be embedded in JSX.
Important JSX rules
- Use
className instead of class for CSS classes.
- Close tags correctly.
- Use a parent element or Fragment for multiple sibling elements.
- Use curly braces to insert JavaScript expressions.
- Use uppercase names for custom React components.
7. Passing Props to Functional Components
Props, short for properties, are inputs passed from a parent component to a child component. They allow the same functional component to display different content based on the values it receives.
Example using a props object
function Student(props) {
return (
<div>
<h2>Name: {props.name}</h2>
<p>Course: {props.course}</p>
</div>
);
}
function App() {
return (
<div>
<Student name="Aarav" course="React JS" />
<Student name="Priya" course="JavaScript" />
</div>
);
}
export default App;
Here, the Student component receives different names and courses through props.
Using destructured props
function Student({ name, course }) {
return (
<div>
<h2>Name: {name}</h2>
<p>Course: {course}</p>
</div>
);
}
Destructuring extracts the required values directly from the props object. Props should be treated as read-only; a component should not directly modify them.
8. Using Default Values for Props
Default parameter values can provide fallback values when a prop is missing or explicitly passed as undefined.
Example
function Greeting({ name = "Guest" }) {
return (
<h2>Hello, {name}!</h2>
);
}
function App() {
return (
<div>
<Greeting name="Aarav" />
<Greeting />
</div>
);
}
Result:
- The first component displays “Hello, Aarav!”.
- The second component displays “Hello, Guest!”.
A default parameter does not replace a value explicitly set to null.
9. Managing State with the useState Hook
State is information that a component remembers between renders. Functional components can use the useState Hook to store and update state.
Syntax
const [state, setState] = useState(initialValue);
state contains the current state value.
setState is the function used to request a state update.
initialValue provides the initial state.
Example: Counter component
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
function handleIncrement() {
setCount(previousCount => previousCount + 1);
}
return (
<div>
<h2>Count: {count}</h2>
<button type="button" onClick={handleIncrement}>
Increase
</button>
</div>
);
}
export default Counter;
How it works
useState(0) initializes the counter to zero.
count stores the current value.
setCount requests a state update.
- The button calls
handleIncrement when clicked.
- React renders the updated count after the state update.
Important: Call Hooks such as useState at the top level of a function component, not inside loops, conditions, or nested functions.
10. Handling Events in Functional Components
Event handlers allow functional components to respond to user interactions, such as clicking a button, typing into a field, or submitting a form.
In JSX, event names use camelCase, such as onClick, onChange, and onSubmit.
Example: Button click
function ClickButton() {
function handleClick() {
alert("Button clicked!");
}
return (
<button type="button" onClick={handleClick}>
Click Me
</button>
);
}
export default ClickButton;
Example: Passing an argument
function CourseButton() {
function handleSelect(courseName) {
alert("Selected course: " + courseName);
}
return (
<button
type="button"
onClick={() => handleSelect("React JS")}
>
Select Course
</button>
);
}
Pass a function to the event handler. Avoid calling the handler immediately during rendering unless you deliberately intend to call it at that point.
11. Conditional Rendering in Functional Components
Conditional rendering means displaying UI based on a condition. Functional components can use regular JavaScript conditions, ternary expressions, or logical AND expressions.
Using an if statement
function LoginMessage({ isLoggedIn }) {
if (isLoggedIn) {
return <h2>Welcome back!</h2>;
}
return <h2>Please log in.</h2>;
}
Using a ternary operator
function Status({ isAvailable }) {
return (
<p>
{isAvailable ? "Available" : "Unavailable"}
</p>
);
}
Using logical AND
function Notification({ messageCount }) {
return (
<div>
{messageCount > 0 && (
<p>You have new messages.</p>
)}
</div>
);
}
Using messageCount > 0 avoids accidentally displaying the number 0 when the count is zero.
12. Rendering Lists in Functional Components
Functional components can render lists by using JavaScript array methods such as map(). Each element in a rendered list should have a stable key that is unique among its siblings.
Example
const courses = [
{ id: 1, name: "React JS" },
{ id: 2, name: "JavaScript" },
{ id: 3, name: "HTML and CSS" }
];
function CourseList() {
return (
<ul>
{courses.map(course => (
<li key={course.id}>
{course.name}
</li>
))}
</ul>
);
}
export default CourseList;
Best practices for lists
- Use
map() to transform array data into JSX elements.
- Provide stable keys, such as database IDs.
- Avoid array indexes as keys when items may be inserted, removed, or reordered.
- Keep list data and presentation logic easy to understand.
13. Using Multiple Functional Components Together
A React application is usually composed of multiple components. Each component handles a particular section of the interface, and a parent component combines them.
Example
function Header() {
return (
<header>
<h1>My Website</h1>
</header>
);
}
function MainContent() {
return (
<main>
<p>Welcome to our website.</p>
</main>
);
}
function Footer() {
return (
<footer>
<p>Thank you for visiting!</p>
</footer>
);
}
function App() {
return (
<>
<Header />
<MainContent />
<Footer />
</>
);
}
export default App;
Here, App is the parent component. It combines Header, MainContent, and Footer into one page.
14. Understanding the Children Prop
The children prop represents content nested between a component's opening and closing tags. It is useful for creating reusable cards, panels, layouts, and wrappers.
Example
function Card({ children }) {
return (
<div className="card">
{children}
</div>
);
}
function App() {
return (
<Card>
<h2>Functional Components</h2>
<p>Create reusable UI elements with React.</p>
</Card>
);
}
The content inside ... is passed to the Card component through its children prop.
15. Using useEffect in Functional Components
The useEffect Hook allows a functional component to synchronize with an external system, such as a network connection, browser API, timer, or third-party widget.
Not every component needs an effect. If a value can be calculated directly from props or state, it is usually better to calculate it during rendering rather than use an effect to store a duplicate value.
Example: Updating the document title
import { useEffect, useState } from "react";
function TitleCounter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<div>
<h2>Count: {count}</h2>
<button
type="button"
onClick={() => setCount(previous => previous + 1)}
>
Increase
</button>
</div>
);
}
export default TitleCounter;
Explanation
useState manages the counter value.
useEffect synchronizes the browser document title with that value.
- The dependency array
[count] tells React when the effect needs to re-synchronize.
- When the count changes, the document title is updated.
16. Functional Components vs. Class Components
React supports both functional components and class components. Function components are recommended for most new React code, while class components remain supported and may be found in existing projects.
| Feature |
Functional Components |
Class Components |
| Definition |
JavaScript function |
JavaScript class extending React.Component |
| UI description |
Returns React elements, often using JSX |
Uses a render() method |
| Props |
Function parameters, often destructured |
this.props |
| State |
Hooks such as useState |
this.state and this.setState() |
| Lifecycle-related behavior |
Hooks such as useEffect for relevant external synchronization |
Lifecycle methods such as componentDidMount |
| Hooks |
Can use Hooks at the top level |
Cannot call Hooks inside class components |
| Syntax |
Generally more concise |
Uses class-specific syntax |
| New development |
Recommended for most components |
Usually used when maintaining existing class-based code |
17. Rules of Hooks in Functional Components
Hooks are special React functions that let function components use React features such as state, context, refs, and effects. Hooks must follow specific rules.
Rule 1: Call Hooks at the top level
Do not call Hooks inside loops, conditions, or nested functions. Call them at the top level of a function component or a custom Hook.
Incorrect:
function Example({ enabled }) {
if (enabled) {
const [count, setCount] = useState(0);
}
return <p>Example</p>;
}
Correct:
function Example({ enabled }) {
const [count, setCount] = useState(0);
if (!enabled) {
return <p>Feature is disabled.</p>;
}
return <p>Count: {count}</p>;
}
Rule 2: Call Hooks from React functions
- Call Hooks from function components.
- Call Hooks from custom Hooks.
- Do not call Hooks from ordinary JavaScript functions that are not React components or custom Hooks.
Rule 3: Do not call a component like a normal function
Render a component using JSX rather than calling it directly.
// Recommended
<Welcome />
// Avoid
Welcome()
18. Best Practices for Functional Components
- Use meaningful component names in PascalCase.
- Keep components small and focused on a clear responsibility.
- Use props to make components reusable.
- Treat props as read-only.
- Use Hooks correctly and follow the Rules of Hooks.
- Keep rendering pure and avoid side effects in the component body.
- Use state only for information that needs to change over time and affect the UI.
- Use stable keys when rendering lists.
- Prefer semantic HTML elements and accessible form controls.
- Use event handlers correctly by passing functions rather than calling them during rendering.
- Avoid unnecessary effects and duplicated state.
- Use a consistent formatting and linting style.
- Test important user interactions and component behavior.
19. Common Mistakes in Functional Components
| Mistake |
Correct approach |
| Using lowercase names for custom components |
Use PascalCase, such as UserProfile. |
| Forgetting to return JSX |
Return the required React elements from the function. |
| Returning sibling elements without a parent |
Use a parent element or Fragment. |
| Calling Hooks inside conditions |
Call Hooks at the top level of the component. |
| Calling a component as a normal function |
Render it with JSX, such as . |
| Modifying props directly |
Pass new data through props or manage changing data with state. |
| Updating state by mutating an array or object |
Create a new array or object and use the state setter. |
| Rendering lists without keys |
Provide stable keys unique among siblings. |
| Putting side effects in the component body |
Use event handlers or an appropriate effect for external synchronization. |
| Using effects to calculate simple derived values |
Calculate values directly during rendering when appropriate. |
20. Practical Project: Student Information Component
This project combines functional components, props, state, event handling, and list rendering to create a small student information interface.
import { useState } from "react";
function StudentCard({ name, course }) {
return (
<article className="student-card">
<h3>{name}</h3>
<p>Course: {course}</p>
</article>
);
}
function StudentList() {
const [students, setStudents] = useState([
{ id: 1, name: "Aarav", course: "React JS" },
{ id: 2, name: "Priya", course: "JavaScript" }
]);
function addStudent() {
setStudents(previousStudents => [
...previousStudents,
{
id: 3,
name: "Rohan",
course: "HTML and CSS"
}
]);
}
return (
<section>
<h2>Student List</h2>
<button type="button" onClick={addStudent}>
Add Student
</button>
{students.map(student => (
<StudentCard
key={student.id}
name={student.name}
course={student.course}
/>
))}
</section>
);
}
export default StudentList;
Note: This introductory example adds a student with a fixed ID. A production application should generate or receive a unique ID for every new student to prevent duplicate keys.
Concepts covered
- Creating functional components.
- Passing data through props.
- Managing state with
useState.
- Handling button clicks.
- Updating arrays without mutating existing state.
- Rendering lists with
map() and keys.
21. Interview Questions and Answers
Q1. What is a functional component in React?
Answer: A functional component is a JavaScript function that returns React elements describing a part of the UI.
Q2. Why are functional components commonly used?
Answer: They have concise syntax, support Hooks, and make it easy to create reusable and maintainable UI components.
Q3. Can a functional component receive props?
Answer: Yes. Props are passed to a function component as an object and can be accessed directly or through destructuring.
Q4. What is the useState Hook?
Answer: useState allows a function component to declare and update state.
Q5. What is the difference between props and state?
Answer: Props are inputs passed to a component, usually by its parent. State is data managed by React that can change over time and cause the UI to update.
Q6. Can a functional component return multiple elements?
Answer: Yes. It can return multiple sibling elements wrapped in a parent element or a React Fragment.
Q7. What is the purpose of useEffect?
Answer: It lets a function component synchronize with external systems, such as subscriptions, network connections, or browser APIs.
Q8. What are the Rules of Hooks?
Answer: Hooks must be called at the top level of function components or custom Hooks, not inside conditions, loops, or nested functions.
Q9. What is the difference between a regular function component and an arrow function component?
Answer: Both can define React function components. They use different JavaScript function syntax, but both can receive props and use Hooks.
Q10. What is a reusable component?
Answer: A reusable component is designed to be rendered in multiple places, often with different props to customize its content or behavior.
Q11. Why are keys important in a list?
Answer: Keys help React identify list items between renders, particularly when items are inserted, deleted, or reordered.
Q12. Are class components still supported by React?
Answer: Yes. Class components are still supported, but function components are recommended for most new React code.
22. Revision Checklist
- Understand the definition of functional components.
- Write components using regular and arrow function syntax.
- Return JSX from a function component.
- Import, export, and render components.
- Pass data through props and use default prop values.
- Manage changing data with
useState.
- Handle user interactions with event handlers.
- Use conditional rendering.
- Render arrays using
map() and stable keys.
- Understand the purpose of
useEffect.
- Follow the Rules of Hooks.
- Apply functional component best practices.
23. Conclusion
Functional components are central to modern React development. They allow developers to create reusable UI elements using JavaScript functions and JSX. By combining functional components with props, state, Hooks, event handling, and component composition, developers can build organized, interactive, and maintainable React applications.
For further learning, visit the JustAcademy React JS Training Course or register for a React JS course demo.
Official React Documentation