Functional Components
Functional components are a fundamental concept in React, allowing developers to create reusable UI elements. They are pure functions that take in props and return JSX elements, making them easy to understand and work with. In this section, we’ll explore how to create and use functional components in React 19.
Basic Example
A basic functional component can be created using the function keyword or as an arrow function. Here’s an example of a simple HelloWorld component:
import React from 'react';
function HelloWorld() {
return <h1>Hello, World!</h1>;
}This component can be used in another component like this:
import React from 'react';
import HelloWorld from './HelloWorld';
function App() {
return (
<div>
<HelloWorld />
</div>
);
}As you can see, functional components are easy to create and use.
Advanced Usage
Let’s consider a more complex example where we need to handle state and events. We’ll create a Counter component that displays a count and allows the user to increment or decrement it:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const handleIncrement = () => {
setCount(count + 1);
};
const handleDecrement = () => {
setCount(count - 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={handleIncrement}>+</button>
<button onClick={handleDecrement}>-</button>
</div>
);
}In this example, we’re using the useState hook to create a state variable count and an setCount function to update it. We’re also defining two event handlers, handleIncrement and handleDecrement, to update the count when the buttons are clicked.
Best Practices
When working with functional components, keep the following best practices in mind:
- Use the
constkeyword to declare components, as they should not be reassigned. - Use the
useStatehook to manage state in functional components. - Use event handlers to handle user interactions, such as button clicks or form submissions.
- Keep your components small and focused on a single task to improve reusability and maintainability.
Key Takeaways
- Functional components are pure functions that take in props and return JSX elements.
- Use the
useStatehook to manage state in functional components. - Use event handlers to handle user interactions.
- Keep your components small and focused on a single task to improve reusability and maintainability.