ARCHITECTURAL PATTERNS

 

React Components - Architectural Patterns

React components can be organized into different architectural patterns to improve the structure and maintainability of your code. Two common patterns are Presentational and Container components.


Presentational Components

Presentational components are concerned with how things look. They receive data and callbacks exclusively via props and have no internal state. These components are often stateless and focus on rendering UI elements.

Definition:

  • Responsibilities: Render UI based on props.
  • Characteristics: Stateless, no side effects.

Example:

function UserProfile(props) {
return ( <div> <h1>{props.name}</h1> <p>{props.bio}</p> </div> ); } // Usage <UserProfile name="Alice" bio="A software developer." />

Output: Displays a user profile with the provided name and bio.

Container Components

Container components are concerned with how things work. They handle the state, manage data fetching, and pass down data and callbacks to Presentational components. These components are often stateful.

Definition:

  • Responsibilities: Manage state and handle business logic.
  • Characteristics: Stateful, often contain side effects.

Example:

class UserContainer extends React.Component {
constructor(props) { super(props); this.state = { name: "Alice", bio: "A software developer." }; } render() { return <UserProfile name={this.state.name} bio={this.state.bio} />; } }

Output: The UserContainer component manages the state and passes it to UserProfile, which renders the UI.

Post a Comment

0 Comments