About Components in React
What is a Component?
-
A component is a reusable, self-contained piece of UI.
-
Think of components as JavaScript functions or classes that return React elements (JSX) describing what should appear on the screen.
-
Components can be small and simple (like a button) or complex and composed of many smaller components.
Why Use Components?
-
Reusability: Write once, use many times.
-
Maintainability: Break UI into manageable chunks.
-
Encapsulation: Each component manages its own structure, styles, and behavior.
-
Composition: Components can contain other components to build complex interfaces.
Types of Components
| Type | Description | Example |
|---|---|---|
| Functional Component | A JavaScript function returning JSX | function Greeting() { return <h1>Hello!</h1>; } |
| Class Component | ES6 class extending React.Component with a render() method |
class Greeting extends React.Component { render() { return <h1>Hello!</h1>; } } |
Functional Components (Modern Standard)
Or using arrow functions:
Class Components (Older Syntax)
Using Components
Props: Passing Data to Components
-
Props are inputs to components — like function arguments.
-
They allow components to be dynamic and reusable.
Example:
The component uses the name prop to customize the output.
State: Components’ Internal Data
-
Components can have state, data that can change over time.
-
Functional components use hooks like
useStatefor state management. -
Class components use
this.state.
Example (Functional with state):
Summary
-
Components are the core building blocks of React.
-
They are reusable, composable, and encapsulate UI and logic.
-
Modern React prefers functional components with hooks.
-
Use props to pass data in, and state to manage internal dynamic data.
