1.9 KiB
React Components
In this section, we will discuss how to create and manage components in React. Components are the building blocks of any React application and can be classified into various types.
What is a Component?
A component in React is a reusable piece of UI that can be managed independently. Components can be classified into class components and functional components. Functional components use hooks
to handle state and lifecycle methods.
Creating a Functional Component
To create a functional component, define a JavaScript function
that returns HTML using JSX syntax. Here’s an example:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
Handling State with useState
useState
is a hook
that allows you to add state to your functional components. It returns an array containing the current state and a function to update it.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
Class Components
Class components are ES6 classes that extend from React.Component
. They must implement a render()
method that returns JSX.
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Lifecycle Methods
Class components have lifecycle methods that you can override to run code at specific times in the component's lifecycle. Some common lifecycle methods include componentDidMount
, componentDidUpdate
, and componentWillUnmount
.
Conclusion
Understanding how to use and manage components effectively in React is crucial for building robust applications. Whether using functional or class components, hooks or lifecycle methods, React provides powerful tools for managing complex UIs.