A Function Component in React is a JavaScript function that returns React elements (JSX) representing the UI.
Contents
Key Characteristics of Function Components:
Feature | Description |
---|---|
Stateless (Before Hooks) | Initially, function components couldn’t hold state, but with React Hooks (introduced in React 16.8), they can now manage state and side effects. |
Simpler Syntax | They are simpler and easier to write compared to class components. |
No this keyword | Unlike class components, there’s no need for this . |
Hooks Support | Can use React Hooks like useState() , useEffect() , etc., to add state and lifecycle functionalities. |
Basic Syntax:
javascriptCopyEditfunction Welcome() {
return <h1>Hello, World!</h1>;
}
OR
javascriptCopyEditconst Welcome = () => {
return <h1>Hello, World!</h1>;
}
Using Props in a Function Component:
javascriptCopyEditfunction Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
OR using destructuring:
javascriptCopyEditfunction Welcome({ name }) {
return <h1>Hello, {name}!</h1>;
}
Using State in a Function Component (with Hooks):
javascriptCopyEditimport { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
Explanation:
useState()
is a React Hook that adds state to the function component.count
is the state variable, andsetCount
is the function to update it.- When button is clicked,
setCount()
updates the state, and the component re-renders.
Advantages of Function Components:
Advantage | Explanation |
---|---|
Simpler and Cleaner | Shorter and more readable compared to class components. |
Better Performance | Slightly faster than class components in some cases because they don’t extend React.Component. |
Hooks Support | Can handle state, side effects, and context using Hooks (useState , useEffect , useContext , etc.). |
No this Binding Issue | No need to bind this , unlike in class components. |
Recommended in Modern React | Preferred over class components after React Hooks were introduced in React 16.8. |
When to Use Function Components:
- For all new React projects.
- When you want a simpler structure.
- When you need state and lifecycle features (using Hooks).
Key Takeaways:
- Function Component → A function returning JSX.
- Before React Hooks → Stateless;
After Hooks → Can hold state and side effects. - Simpler, cleaner, and recommended approach in modern React development.
Let me know if you need more help with React components or any other concept! 🚀😊