The container/presentational component pattern is a design pattern commonly used in React applications to separate concerns and enhance the maintainability of the codebase. This pattern divides components into two distinct types: container components and presentational components. Each type has its own responsibilities, which helps in organizing the application structure and improving reusability.
Container components are responsible for managing state and handling logic, while presentational components focus solely on rendering the UI based on the props they receive. This separation allows developers to create components that are easier to test and reuse across different parts of the application.
Container components, also known as smart components, are responsible for:
For example, consider a simple user profile application:
import React, { Component } from 'react';
import UserProfile from './UserProfile';
class UserProfileContainer extends Component {
state = {
user: null,
loading: true,
};
componentDidMount() {
fetch('/api/user')
.then(response => response.json())
.then(data => this.setState({ user: data, loading: false }));
}
render() {
const { user, loading } = this.state;
return loading ? Loading... : ;
}
}
export default UserProfileContainer;
Presentational components, also known as dumb components, are focused on:
Continuing with the user profile example, here’s how a presentational component might look:
import React from 'react';
const UserProfile = ({ user }) => (
{user.name}
Email: {user.email}
Age: {user.age}
);
export default UserProfile;
When implementing the container/presentational component pattern, consider the following best practices:
While using this pattern, developers may encounter several common pitfalls:
By adhering to the container/presentational component pattern, developers can create a more organized and maintainable codebase, allowing for easier scalability and collaboration within teams.