DEV Community

Vivek Kurmi
Vivek Kurmi

Posted on

Container and Presentational Components

The Container and Presentational Component pattern is a common design approach in React to keep your components organised and maintainable.
This pattern is also known as the Smart and Dumb component pattern.
Let's break down the concepts and provide simple code examples.

Container Components (Smart Components):

Container components are responsible for managing state, data fetching, and handling logic.
They often do not contain much JSX rendering code and are more focused on the functionality of the component.
They are often stateful and may interact with Redux or other state management solutions.
Here's an example of a container component:

import React, { useState, useEffect } from 'react';

function UserListContainer() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    // Simulate fetching user data from an API
    fetch('https://jsonplaceholder.typicode.com/users')
      .then((response) => response.json())
      .then((data) => setUsers(data));
  }, []);

  return <UserList users={users} />;
}

export default UserListContainer;
Enter fullscreen mode Exit fullscreen mode

In this example, UserListContainer is responsible for fetching user data and maintaining the state. It renders a Presentational Component called UserList.

Presentational Components (Dumb Components):

Presentational components are concerned with how things look. They receive data and callbacks as props and are primarily responsible for rendering UI elements.
They are stateless and don't manage application state.
Here's an example of a presentational component:

import React from 'react';

const UserList = ({ users }) => {
  return (
    <div>
      <h2>User List</h2>
      <ul>
        {users.map((user) => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default UserList;
Enter fullscreen mode Exit fullscreen mode

In this example, UserList is a pure presentational component that takes the list of users as a prop and renders them. It does not have any state or logic for data fetching.

The advantages of this pattern include:

  • Separation of concerns: Container components handle data and logic, while presentational components focus on rendering.
  • Reusability: Presentational components can be used in different parts of the application since they are not tightly coupled with data and logic.
  • Testing: Presentational components are easier to test since they don't have complex logic.

By following the Container and Presentational Component pattern, you can create a more organized and maintainable React application, especially as your project grows in complexity.

😍 If you enjoy the content, please 👍 like, 🔄 share, and 👣 follow for more updates!
Join me on a professional journey through my LinkedIn profile: Linkedin Profile

Top comments (0)