Sitemap
Prophet Bestman

Prophet Bestman

Frontend Developer | React JS | Next JS | React native | Technical Writing

React Container/Presentational Pattern

6 min readFeb 9, 2024

--

Press enter or click to view image in full size

What are patterns in React?

Patterns are reusable solutions and best practices that are used for solving common problems that we encounter during our software development process. So while coding a project, you will see yourself writing code that has similar behaviour, similar way of presenting data or manipulating data. We can sometimes come up with our own ways of solving these problems and actually, may be able to get by doing that. However, if we want to build scalable applications that are optimised and are consistent, we have to take certain things into account and one of such is the concept of patterns. We need to have defined ways of solving problems and understand which ways work best for which scenario.

Apart from pattern in software development, React.js as a library has patterns peculiar to it and the problems that are In this article we’ll quickly go through what the Container/Presentational pattern is about, its pros, its cons and whether you should use it or not in 2024.

This is an intermediate level tutorial so for you to be able to follow up this article you should have basic knowledge of React.js. Things like state, props and the rules surrounding hooks. We use tailwind css for styling but it’s not a prerequisite.

We’ll look into the following:

  • What exactly Container/Presentational is
  • Presentational/Stateless Components
  • Presentational/Stateless Components
  • Container/Smart Components
  • Container/Smart Components
  • The pros of this pattern
  • Cons
  • My suggestion to you

What is this Container/Presentational Pattern really?

It goes by several names. “Container/View”, “Smart/Dumb”, “Container/Stateless” I don’t know which other names you might have heard or may hear later.
The idea of this patter is very simple. Separate components based on their responsibility to either manage state or render data. The polished way of saying this is Separation of Concerns.

You should by now know that React runs on state and is about how your application either manages, manipulates or respond to state changes. In light of that, following this pattern would involve you classifying your components into two major categories.

Presentational/Stateless Components

Their primary function is to display the data they receive as prop. They are mostly stateless components i.e they don’t maintain their own state. They do not altar the data they receive either. What they do is just receive data from container components as props and render it. They are mostly used for UI composition (styling and stuff like that 🌚)

Take a look at the example below:

import React from 'react';

const UserCard = ({ name, description, imageUrl }) => {
return (
<div className="max-w-md mx-auto bg-white rounded-xl shadow-md overflow-hidden md:max-w-2xl">
<div className="md:flex">
<div className="md:flex-shrink-0">
<img className="h-48 w-full object-cover md:h-full md:w-48" src={imageUrl} alt="Card image" />
</div>
<div className="p-8">
<div className="uppercase tracking-wide text-sm text-indigo-500 font-semibold">{name}</div>
<p className="mt-2 text-gray-500">{description}</p>
</div>
</div>
</div>
);
};

export default UserCard;
Press enter or click to view image in full size

You will notice that UserCard receives name, description and imageUrl as props and composes a User Interface that renders it to the screen.
In this pattern the component that will wrap UserCard will be the one to proved UserCard with the value it receives in its props.

Container/Smart Components

Their primary function is passing down data to presentational components. They don’t render any other components except the presentational components they pass data down to. They to not have any styling either. They are managing state within the application. They maintain the state and pass it down to presentational components as props. They handle data fetching from external APIs or local data sources. They encapsulate the logic for making API requests, processing responses, and updating the state accordingly. Container components also implement the business logic of the frontend application. They implement algorithms, calculations, and other logic required to manipulate data and produce the desired behaviour.

Get Prophet Bestman’s stories in your inbox

Join Medium for free to get updates from this writer.

Below is an example of A container component and how it is used with presentational components

import React, { useState, useEffect } from 'react';
import UsersGrid from './UsersGrid'; // Assuming Card is a presentational component

const ContainerComponent = () => {
const [data, setData] = useState([]);

useEffect(() => {
// Fetch data from an API endpoint
fetchData();
}, []);

const fetchData = async () => {
try {
// Make API request to fetch data
const response = await fetch('https://api.example.com/data');
const responseData = await response.json();
setData(responseData);
} catch (error) {
console.error('Error fetching data:', error);
}
};

if(!data.length) <p>Loading Users...</p>

if(data.length)
return (
<div>
<Title title="Users List" count={data.length} />
<UsersGrid data={data} />
</div>
);
};

export default ContainerComponent;
const Title = ({title})=> {
return <h1 className="text-3xl font-bold mb-4">{title}</h1>
};
import UserCard from './UserCard'; // Assuming Card is a presentational component

const UsersGrid = ({data})=> {
return(
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{data.map((item, index) => (
<UserCard key={index} name={item.name} description={item.description} imageUrl={item.imageUrl} />
))}
</div>
);
};
Press enter or click to view image in full size

Pros

  • It encourages seperation of concerns. While Container Components focus on getting data and passing it down, Presentational Components focus on composing a User Interface to display the data that is passed to it as props
  • Presentational Components are highly reusable. That’s because they do not contain any state logic. They just receive props and render it. So they need not worry about manipulating the data. That can be handled by the component that renders them. This makes it easy to reuse them in different places within the application
  • Testing presentational components are easy because they are pure functions.

Cons

  • It’s basically an overkill and unnecessarily excess code to create a wrapping component to provide data to its children components.

I’ll do you one better

As I’ve said before, the purpose of patterns is mainly to to provide reusable solutions and best practices for solving common problems. So what is the main problem the Container/Presentational pattern solves? The Container/Presentational pattern addresses the challenge of separating concerns within a React application. By dividing components into container components and presentational components, this pattern fosters a clear distinction between logic and presentation.

When the problem is properly defined, it’s easy to some up with solutions and evaluate previous solutions. Its with this in mind that I’ll talk about more preferable alternative to this pattern is solves the problem in a more elegant way.

Hooks
Yes, hooks totally eliminates the need for the Container/Presentational patten. Therefore, instead of creating a container component to wrap the presentational component, we just create a hook that abstracts the logic we have and provide the directly within the component we need it. This not only makes the components reusable, it makes the logic also reusable.

Let's refactor the above code to use hooks instead of the initial pattern used above.

import { useState, useEffect } from 'react';

const useUserData = () => {
const [data, setData] = useState([]);
const [isLoading, setIsLoading] = useState(true);

useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
const responseData = await response.json();
setData(responseData);
} catch (error) {
console.error('Error fetching data:', error);
} finally {
setIsLoading(false);
}
};

fetchData();
}, []);

return { data, isLoading };
};

export default useUserData;
import React from 'react';
import useUserData from './useUserData'; // Import the custom hook
import UsersGrid from './UsersGrid'; // Assuming Card is a presentational component

const ContainerComponent = () => {
const { data, isLoading } = useUserData();

if (isLoading) return <p>Loading Users...</p>;

return (
<div>
<Title title="Users List" count={data.length} />
<UsersGrid data={data} />
</div>
);
};

export default ContainerComponent;
Press enter or click to view image in full size

So at the end of the day, we end up getting the same result but with better reusability and less components in our component tree.

If you find this helpful, I’d like to know so that I can keep writing artcles like this one. You can also drop your questions, or additions. Someone else may learn from you.

Don’t forget to follow me, so you can be seeing more content like this one and level up your game as a developer.

Next, I’ll be talking about the Render Props Pattern, and it’s gonna be interesting.

--

--

Prophet Bestman
Prophet Bestman

Frontend Developer | React JS | Next JS | React native | Technical Writing