REACT
React Components: Syntax, Usage, and Examples
React components define how UI elements should appear and behave. Each component is a self-contained unit that renders a part of the interface and manages its own logic. By using components, you can build complex applications with reusable and maintainable code.
How to Use React Components
Use React components to break down the UI into smaller, manageable parts. Components in React can be either functional or class-based, each serving a different purpose.
Functional Components
Functional components are JavaScript functions that return JSX. They are the preferred approach in modern React development due to their simplicity and performance benefits.
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
export default Greeting;
Use functional components when you don’t need lifecycle methods or complex state logic. With React hooks, you can also add state and side effects when necessary.
Class Components
Class components are ES6 classes that extend React.Component
and must include a render
method.
import React, { Component } from "react";
class Greeting extends Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
export default Greeting;
Use class components if you need to manage component lifecycle methods, but keep in mind that Hooks have largely replaced this need.
When to Use React Components
React components allow you to build scalable, maintainable interfaces. Use them when your application requires:
Reusability
If you find yourself writing the same UI structure multiple times, create a reusable component. For example, a Button
component can standardize button styles across the application.
function Button({ text, onClick }) {
return <button onClick={onClick}>{text}</button>;
}
State Management
Components can store and manage their own state, enabling interactive UI elements like forms, modals, and counters.
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}
Use stateful components to handle user interactions and data changes dynamically.
Component Communication
Pass data between components using props. This allows child components to receive dynamic values from their parent.
function Profile({ username }) {
return <h2>Welcome, {username}!</h2>;
}
function App() {
return <Profile username="Alice" />;
}
Props make components flexible by allowing different content to be rendered based on parent component data.
Examples of React Components
React components make UI development modular and efficient. Below are common use cases:
Rendering Lists Dynamically
When dealing with dynamic data, use the .map()
method to generate a list of elements.
const users = ["Alice", "Bob", "Charlie"];
function UserList() {
return (
<ul>
{users.map((user) => (
<li key={user}>{user}</li>
))}
</ul>
);
}
Use unique keys to optimize rendering performance and prevent unnecessary re-renders.
Form Handling
React components handle form inputs using controlled components, where form elements are tied to state.
import { useState } from "react";
function LoginForm() {
const [username, setUsername] = useState("");
return (
<div>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<p>You entered: {username}</p>
</div>
);
}
Use controlled components to synchronize form input values with state, ensuring real-time updates.
Conditional Rendering
Use conditional rendering to display different components based on conditions.
function Status({ isLoggedIn }) {
return isLoggedIn ? <p>Welcome back!</p> : <p>Please log in.</p>;
}
This approach simplifies UI logic by keeping conditions inside JSX expressions.
Learn More About React Components
Component Lifecycle
Class components have lifecycle methods like componentDidMount
, componentDidUpdate
, and componentWillUnmount
. However, functional components handle side effects using the useEffect
hook.
import { useEffect } from "react";
function FetchData() {
useEffect(() => {
console.log("Component mounted");
}, []);
return <p>Data is loading...</p>;
}
Use useEffect
to run code when a component mounts, updates, or unmounts.
React Component Library
Pre-built component libraries like Material-UI, Ant Design, and Chakra UI provide ready-to-use UI components, reducing development time.
import Button from "@mui/material/Button";
function App() {
return <Button variant="contained">Click Me</Button>;
}
Using a component library ensures consistency in UI design while allowing customization.
React Server Components
React Server Components (RSC) optimize performance by rendering components on the server, reducing the amount of JavaScript sent to the client. Unlike traditional client-side components, they don’t include interactivity or state.
Handling Lists of Components in React
Use lists of components when you need to render multiple items dynamically.
const tasks = ["Buy groceries", "Walk the dog", "Read a book"];
function TaskList() {
return (
<ul>
{tasks.map((task, index) => (
<li key={index}>{task}</li>
))}
</ul>
);
}
Use keys to help React track changes efficiently and prevent unnecessary re-renders.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.