React - Essential Basics
Now that we've seen how to set up a React project with Vite, we're going to delve into the fundamental concepts of React!
React Components - Deep Dive
What is a Functional Component?
A functional component is simply a JavaScript function that returns JSX. It is the most common and recommended type of component in modern React.
Definition: A React component is "a JavaScript function that you can sprinkle with markup"!
Functional Components vs Class Components
// ✅ Functional Component (RECOMMENDED)
function MyComponent() {
return <h1>Hello World!</h1>
}
// ❌ Class Component (DEPRECATED)
class MyComponent extends React.Component {
render() {
return <h1>Hello World!</h1>
}
}
Why functional components?
- Simpler to write and understand
- Less boilerplate code
- Hooks to manage state and side effects
- Optimized performance
- Official React recommendation
Possible syntaxes
// Function declaration
function MyComponent() {
return <h1>Hello World!</h1>
}
// Arrow function
const MyComponent = () => {
return <h1>Hello World!</h1>
}
// Shortened arrow function (without explicit return)
const MyComponent = () => <h1>Hello World!</h1>
// With props destructuring
const MyComponent = ({ title, subtitle }) => (
<div>
<h1>{title}</h1>
<p>{subtitle}</p>
</div>
)