Components are the fundamental building blocks of React applications. They allow you to break down the UI into reusable and manageable pieces. Each component is a JavaScript function or class that returns a React element, which describes how the UI should appear.
Function Components:
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
// Usage
<Greeting name="Sara" />
Class Components:
React.Component
and must have a render()
method that returns JSX. They can have state and lifecycle methods.class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
// Usage
<Greeting name="Sara" />
Props:
props
in function components or this.props
in class components.function Welcome(props) {
return <h1>Welcome, {props.username}!</h1>;
}
// Usage
<Welcome username="John" />
State:
useState
hook. In class components, state is managed using the this.state
object and this.setState()
method.import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
Lifecycle Methods:
componentDidMount
, componentDidUpdate
, and componentWillUnmount
.useEffect
hook.import React, { useEffect } from 'react';
function Example() {
useEffect(() => {
// Side effect code here
console.log('Component mounted or updated');
return () => {
// Cleanup code here
console.log('Component unmounted');
};
}, []); // Empty dependency array means this effect runs only on mount and unmount
return <div>Check the console for lifecycle messages</div>;
}
Component Composition:
function Header() {
return <header><h1>My App</h1></header>;
}
function Footer() {
return <footer><p>© 2024 My App</p></footer>;
}
function App() {
return (
<div>
<Header />
<main>
<h2>Welcome to My App</h2>
</main>
<Footer />
</div>
);
}
Components in React are the core building blocks of an application. They can be defined as function components or class components, with each serving different needs. Components use props to receive data, manage their own state to track changes, and can utilize lifecycle methods or hooks to handle side effects and manage their lifecycle. Component composition allows for creating complex UIs by combining simpler components, making React a powerful and flexible library for building interactive user interfaces.
@aCodeTutorials All Rights Reserved
privacy policy | about