Interested in our next book? Learn more about Building Large-scale JavaScript Web Apps with React

Design Pattern

Container/Presentational Pattern

In React, one way to enforce separation of concerns is by using the Container/Presentational pattern . With this pattern, we can separate the view from the application logic.

Let’s say we want to create an application that fetches 6 dog images, and renders these images on the screen.

Ideally, we want to enforce separation of concerns by separating this process into two parts:

  • Presentational Components : Components that care about how data is shown to the user. In this example, that’s the rendering the list of dog images .
  • Container Components : Components that care about what data is shown to the user. In this example, that’s fetching the dog images .

Fetching the dog images deals with application logic , whereas displaying the images only deals with the view .

Presentational Component

A presentational component receives its data through props . Its primary function is to simply display the data it receives the way we want them to, including styles, without modifying that data.

Let’s take a look at the example that displays the dog images. When rendering the dog images, we simply want to map over each dog image that was fetched from the API, and render those images. In order to do so, we can create a functional component that receives the data through props , and renders the data it received.

The DogImages component is a presentational component. Presentational components are usually stateless: they do not contain their own React state, unless they need a state for UI purposes. The data they receive, is not altered by the presentational components themselves.

Presentational components receive their data from container components .

Container Components

The primary function of container components is to pass data to presentational components, which they contain . Container components themselves usually don’t render any other components besides the presentational components that care about their data. Since they don’t render anything themselves, they usually do not contain any styling either.

In our example, we want to pass dog images to the DogsImages presentational component. Before being able to do so, we need to fetch the images from an external API. We need to create a container component that fetches this data, and passes this data to the presentational component DogImages in order to display it on the screen.

Combining these two components together makes it possible to separate handling application logic with the view.

In many cases, the Container/Presentational pattern can be replaced with React Hooks. The introduction of Hooks made it easy for developers to add statefulness without needing a container component to provide that state.

Instead of having the data fetching logic in the DogImagesContainer component, we can create a custom hook that fetches the images, and returns the array of dogs.

By using this hook, we no longer need the wrapping DogImagesContainer container component to fetch the data, and send this to the presentational DogImages component. Instead, we can use this hook directly in our presentational DogImages component!

By using the useDogImages hook, we still separated the application logic from the view. We’re simply using the returned data from the useDogImages hook, without modifying that data within the DogImages component.

Hooks make it easy to separate logic and view in a component, just like the Container/Presentational pattern. It saves us the extra layer that was necessary in order to wrap the presentational component within the container component.

There are many benefits to using the Container/Presentational pattern.

The Container/Presentational pattern encourages the separation of concerns. Presentational components can be pure functions which are responsible for the UI, whereas container components are responsible for the state and data of the application. This makes it easy to enforce the separation of concerns.

Presentational components are easily made reusable, as they simply display data without altering this data. We can reuse the presentational components throughout our application for different purposes.

Since presentational components don’t alter the application logic, the appearance of presentational components can easily be altered by someone without knowledge of the codebase, for example a designer. If the presentational component was reused in many parts of the application, the change can be consistent throughout the app.

Testing presentational components is easy, as they are usually pure functions. We know what the components will render based on which data we pass, without having to mock a data store.

The Container/Presentational pattern makes it easy to separate application logic from rendering logic. However, Hooks make it possible to achieve the same result without having to use the Container/Presentational pattern, and without having to rewrite a stateless functional component into a class component.Note that today, we don’t need to create class components to use state anymore.

Although we can still use the Container/Presentational pattern, even with React Hooks, this pattern can easily be an overkill in smaller sized application.

  • Presentational and Container Components - Dan Abramov

Separation of Concerns in React –How to Use Container and Presentational Components

Keyur Paralkar

Many new React developers combine logic and presentation inside the same React component. And they may not know why it's important to separate these two – they just want to make it work.

But later, they'll find that they need to make changes to the file and doing so becomes a humungous task. Then they'll have to re-work things to separate these two parts.

This comes from not knowing about the separation of concerns and the presentation and container components pattern. That's why I'm going to teach you about them so you can mitigate this problem early in your project's development lifecycle.

In this article, we are going to dive into container and presentational components and briefly touch on the concept of separation of concerns.

Without further ado, let's get started!

Table of Contents

  • What is the separation of concerns?
  • What are presentation and container components?
  • Why do we need these components?
  • Presentation and container component example
  • How to replace container components with React hooks

What is the Separation of Concerns?

Separation of concerns is a concept that is widely used in programming. It states that logic that performs different actions should not be groupled or combined together.

For example, what we discussed in the introduction section violates the separation of concerns, because we placed the logic of fetching the data and presenting the data in the same component.

To solve this and to adhere to the separation of concerns, we should separate these two pieces of logic – that is, fetching data and presenting it on the UI – into two different components.

This is were the container and presentation component pattern will help us solve this issue. In the following sections, we are going to dive deep into this pattern.

What are Container and Presentational Components?

To achieve a separation of concerns we have two types of components:

Container components

Presentational components.

These are the components that provide, create, or hold data for the children components.

The only job of a container component is to handle data. It does not consist of any UI of its own. Rather, it consists of presentational components as its children that uses this data.

A simple example would be a component named FetchUserContainer that consists of some logic that fetches all the users.

These are the components whose primary responsibility is to present the data on the UI. They take in the data from the container components.

These components are stateless unless they need their own state for rendering the UI. They do not alter the data that they receive.

An example of this would be a UserList component that displays all the users.

Why Do We Need These Components?

To understand this, let's take a simple example. We want to display a list of posts that we fetch from the JSON placeholder API . Here is the code for the same:

Here is what this component does:

  • It has 3 state variables: posts , isLoading , and error .
  • We have a useEffect hook that consists of the business logic. Here we are fetching the data from the API: [https://jsonplaceholder.typicode.com/posts](https://jsonplaceholder.typicode.com/posts) with the fetch API .
  • We make sure that when the data is fetched, we store it in the posts state variable using setPosts .
  • We also make sure that we toggle the isLoading and error values during the respective scenarios.
  • We put this entire logic inside an async IIFE.
  • Finally, we return the posts in the form of an unordered list and map through all the posts that we fetched earlier.

The problem with the above is that the logic of fetching the data and displaying the data is coded into a single component. We can say that the component is now tightly coupled with the logic. This is the exact thing that we don’t want.

Below are some reasons as to why we require container and presentational components:

  • They help us create components that are loosely coupled
  • They help us maintain separation of concerns
  • Code refactoring becomes much easier.
  • Code becomes more organized and maintainable
  • It makes testing much easier.

Presentation and Container Component Example

Ok, enough talk – let’s get things working by starting off with a simple example. We are going to use the same example as above – fetching the data from a JSON placeholder API.

Let's understand the file structure here:

  • Our container component will be PostContainer
  • Posts : A component that has an unordered list.
  • SinglePost : A component that renders a list tag. This will render each element of the list.

Note: We are going to store all the above components in a separate folder named components .

Now that we know which things go where, let's start off with the container component: PostContainer . Copy-paste the below code into the components/PostContainer.tsx file

From the example we saw in the previous section of this article, the above code just contains the logic of fetching the data. This logic is present in the useEffect hook. Here this container component passes this data to the Posts presentational component.

Let's have a look at the Posts presentational component. Copy-paste the below code in the components/Posts.tsx file:

As you can see, this is a simple file that consists of a ul tag – an unordered list. This component then maps over the posts that are being passed as props. We pass each to the SinglePost component.

There is another presentational component that renders the list tag, that is the li tag. It displays the title and the body of the post. Copy-paste the below code in the components/SinglePost.tsx file:

These presentational components, as you can see, just display the data on the screen. That’s all. They don’t do anything else. Since they are just displaying the data here, they will also have their own styling.

Now that we have setup the components, let's look back on what we have achieved here:

  • The concept of separation of concerns is not violated in this example.
  • Writing unit tests for each component becomes easier.
  • Code maintainability and readability are much better. Thus our codebase has become much more organized.

We have achieved what we wanted here, but we can further enhance this pattern with the help of hooks.

How to Replace Container Components with React Hooks

Since React 16.8.0 , it has become so much easier to build and develop components with the help of functional components and hooks.

We are going to leverage these capabilities here and replace the container component with a hook.

Copy-paste the below code in the hooks/usePosts.ts file:

Here we have,

  • Extracted logic that was present in the PostContainer component into a hook.
  • This hook will return an object that contains the isLoading , posts , and error values.

Now we can simply remove the container component PostContainer . Then, rather than passing the container's data to the presentational components as a prop, we can directly use this hook inside the Posts presentational component.

Make the following edits to the Posts component:

By making use of hooks we have eliminated an extra layer of component that was present on top of these presentational components.

With hooks, we achieved the same results as that of the container/presentational components pattern.

So in this article, we learned about:

  • Separation of concerns
  • Container and presentational components
  • Why we need these components
  • How hooks can replace container components

For further reading I would highly recommend going through the react-table: . This library extensively uses hooks and it has great examples.

You can find the entire code for this article in this codesandbox .

Thanks for reading!

Follow me on  Twitter ,  GitHub , and  LinkedIn .

Front-end developer👨‍💻; Book enthusiasts📖

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Cory Rylan

My name is Cory Rylan , Google Developer Expert , Speaker, Software Developer . Building Design Systems and Web Components .

Angular Design Patterns: Feature and Presentation Components

- 4 minutes

This article has been updated to the latest version Angular 17 and tested with Angular 16. The content is likely still applicable for all Angular 2 + versions.

In this post, we will cover the Feature and Presentation Component Design pattern. This pattern has been called many things such as

  • Smart/Dumb Components
  • Stateful/Stateless Components
  • Container Components

For this post, we will use the terminology of Feature and Presentation. This pattern has been covered many times and across other frameworks other than Angular but I would just like to give my perspective on this useful pattern.

The Component

What is a Feature or Presentation Component? First let's define what a component is. A component is simply a small encapsulated piece of a user interface. Many frameworks and libraries use components including Angular , React , Ember , and Vue . Components allow us to break a large complex UI into smaller easier to understand pieces. This is similar to the way we break our code up into smaller functions. This makes our UI easier to understand and reuse in our applications.

When building large UI systems with components our application it becomes a tree-like structure. Components get used inside of other components. Most of the time these parent-child relationships need to communicate back and forth. In Angular components, we communicate via Input properties and Output events. Parent components can set a property of a child component, and a child component can emit events up to parent components.

This makes it clear where data is flowing from, but it brings up a few questions. Who should fetch data from the server? Which component is responsible for saving the data? This is where Feature and Presentation Components come in.

Feature vs. Presentation

In our web applications, we can take advantage of the Feature and Presentation Component pattern. Let's look at the example app below.

Here we have a product search page. The user can search for products with filters. The search view shows a list of product items.

Let's define the Feature component first. A Feature component is a top-level component that contains all other components in our feature. This commonly is a routed component in Angular. Our feature components are responsible for gathering data from various services for our feature to use. If our user saves data, the feature component is responsible for passing that data to our Angular Services to save the data to our server API. Feature components are still very slim with the amount of application logic. We try to defer this logic to Services if possible. For this example, the product-search is our Feature Component and will be composed of many Presentation components.

Where do Presentation Components fit in? As our Search Feature component grows in complexity, we can refactor our component into smaller reusable Presentation Components. Presentation Components behave like pure functions taking in the data via @Input and emitting data via @Output . This allows the majority of our UI not to know the underlying implementation detail of where the data came from. For example, a product-item component takes in a @Input of a product to display. This allows the product-item component to have the only responsibility of rendering the product when the data is passed to it.

Our product-item could also have a single @Output to notify the feature component when a user clicks a product in the list. This is useful because we can now use the item component for different situations whether that should display a different view or save some information to our API.

Presentation components do not have to be reusable. Keeping the pure Inputs and Outputs makes it easier to debug features. Because our Feature Component is the only component communicating with Services it is easy to determine where the data is coming from and in turn, making it easier to debug.

There are downsides to this though. As the feature grows in complexity, we may have a deeply nested component structure. Since component events only bubble up one level at a time, we will have to pass up to each parent component manually. Sometimes introducing other sub feature or container components can help elevate this. At this point, it brings into question how to manage state which can be for another blog post :)

Presentation Components do take more time to create and hook up than just having large single Feature Components but in the long term can help the maintainability and reusability of our components. Many if not most Presentation Components can be abstracted into a style guide or UI library for the project. To get ideas of component design and style guide maintainability I recommend Brad Frost's fantastic book Atomic Design .

Angular Form Essentials

Angular Form Essentials

Forms can be complicated. Become an expert using Angular Reactive Forms and RxJS . Learn to manage async validation , build accessible , and reusable custom inputs . Get a jump start on building Angular Forms today!

No spam. Short occasional updates on Web Development articles, videos, and new courses in your inbox.

Related Posts

Creating dynamic tables in angular.

Learn how to easily create HTML tables in Angular from dynamic data sources.

Reusable Component Patterns - Default Slots

Learn about how to use default slots in Web Components for a more flexible API design.

Reusable Component Anti-Patterns - Semantic Obfuscation

Learn about UI Component API design and one of the common anti-patterns, Semantic Obfuscation.

DEV Community

DEV Community

Heritier Akilimali

Posted on Jan 17, 2022

An Overview of Presentational and Container Component Pattern.

JavaScript's popular React library is known for its unopinionated nature.

No matter how you view React, there is no denying that it is hands-off approach to how developers should build their applications, giving developers and developer teams the freedom to build the apps the way they want.

As you study other React applications and work on different React applications built with different teams, you notice some common design patterns.

Let's take a look at a popular design pattern for building React applications, you are gonna love it.

Presentation Components

The look and feel of the UI depends on these components. Besides displaying data, they have no dependencies within the application. Consider a list:

It is only responsible for displaying the data passed as props on the User interface in the example above. These components can be written as class components or as stateless functional components that can be tied to UI state

Managing its state in the example above is the responsibility of the TextInput class component.

Container Components

The Container components have a greater impact on the way things work than Presentational components. They typically contain presentation methods and methods for the lifecycle. They also fetch data.

In the example above, we created a SeriesContainer component that fetches data from an API when it mounts. Furthermore, that data is passed to the presentational component ListOfItems. This pattern has the advantage of separating concerns and reusing components. The ListOfItems presentational component is not closely coupled with the SeriesContainer, so any Container component can use it to display data

Final take away

Dan Abramov came up with this design pattern to distinguish presentational components from container components. The presentational ones are responsible for the look, while the container ones are in charge of managing the state. Despite being more popular before, you can still use this pattern wherever you see fit.

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

akshat0610 profile image

Day 24 of 30 of JavaScript

Akshat Sharma - Jul 1

madza profile image

19 Frontend Resources Every Web Developer Must Bookmark 🎨✨

Madza - Jul 9

imabhinavdev profile image

Understanding Declarative Programming in React

Abhinav Singh - Jun 30

skipperhoa profile image

⚡ MyFirstApp - React Native with Expo (P23) - Update Layout Splash Screen

Hòa Nguyễn Coder - Jul 4

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Container/Presentation Pattern

Lydia Hallie

Lydia Hallie

A Tour of JavaScript & React Patterns

Check out a free preview of the full A Tour of JavaScript & React Patterns course

The "Container/Presentation Pattern" Lesson is part of the full, A Tour of JavaScript & React Patterns course featured in this preview video. Here's what you'd learn in this lesson:

Lydia explains how the container presentation pattern enforces a separation of concerns by abstracting the view from the application logic. Presentational components focus on how the data is shown to the user. Container components are responsible for the data passed to the presentational component.

Transcript from the "Container/Presentation Pattern" Lesson

[00:00:00] >> Well, I think that kind of concludes the whole design patterns section of this workshop. So we talked about the module pattern, singleton pattern, proxy pattern, observer pattern, factory pattern and prototype pattern. But the next one is not so much on like the JavaScript design patterns are more on react patterns.

[00:00:15] And these, I'll talk about how we can use different components, how their data is shared and just their relationship to each other. So, first let's talk about the Container Presentational Pattern. So with the container presentational pattern, we essentially have two components. I'm just going to make this real quick.

[00:00:32] We have a container components, which is a component that's solely responsible for retrieving data. And then we have a presentational component which is solely responsible for showing data, rendering data. So because the container component is only fetching data, it usually doesn't like render any styled components, it just renders the presentational components.

[00:00:55] So, when we look at the implementation here, this is using React hooks. By the way most of my examples I will use React hooks. I will also cover the hooks pattern so you can kind of see how the different patterns relate to how we can implement hooks nowadays.

[00:01:10] So I do like assume that you know how hooks work. But if there are any questions about, like these basic like use of XQ state hooks, of course, do let me know. Yeah, so in this implementation, we have the listings container components and container components responsible for fetching data.

[00:01:24] And we can see that here because it's fetching, like listings from an API or like a CMS sets the state to have those listings and then passes them down to the listings component. Are like that the presentational component. I feel like this should have been the presentational component this may be a typo in my end.

[00:01:41] So what we have here is we have that listing container component that you saw before. So this one fetches listing from our API passes down to this listings component which here's just called listings which is probably why I made the mistake. But this is a presentational components. So in here it retrieves this the listings as props and the only thing he cares about is rendering that data in a styled way.

[00:02:05] I'm just getting roads screenly. Yeah, so that was the container presentational pattern. Now, there are many trade offs or benefits to using this pattern. As you can see, there's definitely a separation of concerns. Because the presentational components can be just responsible for the UI. Like just the styling of how are we going to render that data.

[00:02:29] Whereas like container components are just responsible for the state of the data of the application. Yeah, it's also super easy that way to like reuse these presentational components. Maybe they are using like different data sources different data but they're render the content the same way. So we can reuse this presentational components even though they like retrieve different data from props.

[00:02:53] It's also nice if you have many presentational components that don't really touch the fetching logic. So, if you just care about the design or you maybe you're a designer, you don't really know what gets returned from the API. You can make a lot of changes to these presentational components without maybe accidentally like making a mistake with that data how data is fetched and all that stuff.

[00:03:14] Now, of course like Hooks we will see later how Hooks kind of replace this pattern a lot of the time we don't really necessarily have to use this container presentational pattern anymore. Or as much as we had to when we used classes just because it was like more work to like create a class all that stuff but we will see that a bit later.

[00:03:31] All right, so the exercise even though I kind of already showed you the solution here but we see an exercise here. So right now, we just have one component it's called the listings components. But then this component, it's not split up into two separate parts. We don't have like a container part or a presentational part, it's just one big component.

[00:03:50] So what I would like you to do is to split this up into two components, a container components and a presentational components. So the container component responsible for fetching the data and then the presentational components responsible for showing the data. Now, you can I guess already kind of see I've already created the folder structure for you.

[00:04:09] So you have like presentational here and then container here. So you can just type the container code right in the container listings file.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops

How-To Geek

What are presentational and container components in react.

4

Your changes have been saved

Email Is sent

Please verify your email address.

You’ve reached your account maximum for followed topics.

Google Begins Testing 50 Gig Fiber Internet

How i stream music all over my house with home assistant, 8 things you should do after purchasing a new windows laptop, quick links, is there any state, looking at examples, characteristics of each type, advantages of separating presentational and container components.

React has a component-based architecture that encourages you to split your codebase into reusable units of functionality. Not all components are created equal though. Let's look at the differences between two common types, Presentational and Container (also known as "Stateful") components.

To begin with, it should be stressed that these terms don't refer to any specific React feature. They describe a style of writing React components which helps to maintain modularity and separate out concerns. The existence of the two component types arises from choices made in your codebase.

There's only one distinguishing factor: container components have state and presentational components do not. In practice, this means that a container component always makes a call to React's

method. A presentational component will never make use of state.

Here's a simple presentational component:

import React from "react";

class Presentational extends React.Component {

return <h1>{this.props.title}</h1>;

export default Presentational;

The component is extremely simple. It renders a single

tag which displays text passed into the component via its

prop. Let's now look at a stateful container component:

class Container extends React.Component {

constructor(props) {

super(props);

this.state = {

time: (new Date()).toString()

componentDidMount() {

setInterval(() => {

this.setState({time: (new Date()).toString()});

return <h1>{this.state.time}</h1>;

export default Container;

The container component's

method is almost identical to that in the presentational component. The difference is the container component sources its text from inside itself, instead of relying on an outside value passed in as a prop.

Each second, the container component calls

to update the

key in its state. This causes React to re-render the component and display the new time. Our container possesses its own state.

Several unique characteristics tend to arise within both presentational and container components. Looking at presentational components first, the bulk of their code is likely to exist within the

method. They'll contain very little logic as their behaviour is defined by the outside world.

Presentational components are blissfully unaware of where their data is coming from. They don't know when (or whether) it will change. Some examples may not even accept props. Here's a decorational element which simply renders a specific image file:

Container components are much the opposite of their presentational counterparts. You'll typically find most of your site's logic ends up within a container component. The

method may be comparatively short as you'll be spending many more lines fetching data from external sources, transforming it to suit your needs and then storing it into state.

A container component's

method could consist of a single line that renders a presentational component. You've now got strong separation of concerns, with both components having a distinct role that fully respects the other's. The container component sources the data; the presentational component puts it on the screen.

Here's how this looks in practice:

const View = ({title, body}) => (

<div>

<h1>{title}</h1>

<p>{body}</p>

</div>

class BlogPostComponent extends React.Component {

fetch("/blog-post.json")

.then(response => response.json());

.then(blog => this.setState({blog}));

title={this.state.blog.headline}

body={this.state.blog.content} />

is our container component. It loads a post over the network. The data then gets given to the

component for rendering.

doesn't care where it gets its data from - in the future, we could reuse it to display posts fetched from a third-party API such as Facebook or Twitter.

Container components are so called because they tend to encapsulate entire functional areas of your app. They make your project work and represent the app's backend systems.

In a real codebase,

would have even more responsibility. It would need to track whether the post has loaded and handle errors during the network fetch. Consequently, the

method may incorporate some basic logic to alter what gets displayed - either an error message, a progress bar or our presentational

component. Presentational components never have any greater responsibility than rendering a specific section of the UI into the DOM.

Using this pattern helps you to organise your codebase and prevents components from becoming too unwieldy. Although it's not a hard-and-fast rule, diligent separation of the two types improves maintainability as your project's component count grows.

Try to look for opportunities to refactor as a container component's

method grows. It's likely you could take much of its contents and split it into a new presentational component. This makes it easier to reuse the presentational code in the future. It ends up self-contained and capable of operating independently of any specific data source.

Stateful components are less likely to be reused. Non-trivial behaviours naturally accumulate within them, resulting in dependencies on the outside world. That's not to say they can't be reused though - a two-stage confirmation button will contain internal state (to determine whether to display "Reset User's Password" or "Are You Sure?") but will also be deployed throughout your codebase.

Perhaps more than anything, intentionally distinguishing between Presentional and Container components keeps you aware of where your application's state lies. Minimising the number of components with state contributes towards a maintainable codebase and helps to separate concerns.

If you can't decide whether a component should hold state, keep coding and refactor later - it's probably too early in your project's lifecycle to know where the complexity (and hence the state) will congregate.

  • Programming

Container/Presentational Pattern

Enforce separation of concerns by separating the view from the application logic.

We can use the Container/Presentational pattern to separate the logic of a component from the view. To achieve this, we need to have a:

  • Presentational Component, that cares about how data is shown to the user.
  • Container Component, that cares about what data is shown to the user.

For example, if we wanted to show listings on the landing page, we could use a container component to fetch the data for the recent listings, and use a presentational component to actually render this data.

Implementation #

We can implement the Container/Presentational pattern using either Class Components or functional components.

Tradeoffs #

Separation of concerns : Presentational components can be pure functions which are responsible for the UI, whereas container components are responsible for the state and data of the application. This makes it easy to enforce the separation of concerns.

Reusability : We can easily reuse the presentational components throughout our application for different purposes.

Flexibility : Since presentational components don't alter the application logic, the appearance of presentational components can easily be altered by someone without knowledge of the codebase, for example a designer. If the presentational component was reused in many parts of the application, the change can be consistent throughout the app.

Testing : Testing presentational components is easy, as they are usually pure functions. We know what the components will render based on which data we pass, without having to mock a data store.

Not necessary with Hooks : Hooks make it possible to achieve the same result without having to use the Container/Presentational pattern.

For example, we can use SWR to easily fetch data and conditionally render the listings or the skeleton component. Since we can use hooks in functional components and keep the code small and maintainable, we don't have to split the component into a container and presentational component.

Overkill : The Container/Presentational pattern can easily be an overkill in smaller sized application.

We have a Listings component that both contains the fetching logic, as well as the rendering logic. In order to make the fetching logic more reusable, we can split this component up into a container and presentational component.

Challenge #

Remove the data fetching logic from the Listings component, and move this to a separate ListingsContainer component located in /components/container/Listings.tsx

On This Page

  • Implementation

Hashnode Headless CMS

Presentational And Container Component With React

Samuel Christopher's photo

A basic article that explores React patterns, the uses, and differences between Presentational and Container Components.

Target Audience

This article is for both old and newbies to Reactjs. Anyone that wants to learn a pattern of building React applications.

Learning Objectives

After reading this article, you will know how to do the following:

  • Identify a presentational component.
  • Create a presentational component.
  • Know how to use the presentational components.
  • Identify a container component
  • Create a container component.
  • Know how to use container components.
  • Differentiate presentation from container component.

This article will improve your knowledge of how to use the Presentational and Container components in React. It won't make you become an expert in React. It takes lots of consistency and practice to become one.

Introduction

I recently planned to upgrade my skills in web development from mid-lever to senior. Although, I've built and managed full-stack projects working as a freelancer. But I wasn't certain about my skill level, so I started the challenge.

A few months ago, I started studying React patterns. I learned a lot in process of learning. I have always been intentional with the way I structure my code and folder. I learned my approach was not consistent and doesn't help with the management of my codebase. This makes it harder to maintain as the gets bigger and bigger.

Now, this article discusses React component design pattern. A design pattern for building Reacts applications. This involves the separation of components into two buckets. These buckets are called presentational and container.

Presentation

It describes a pattern in React that’s concerned with how things look. It is mostly used to render data on the page. One way to do this, you create a child component that takes data from the parent component as props and renders it on the page.

The following describes a presentation better.

  • How things look
  • Little to no state
  • Receive all data via props
  • Functional Component
  • Same use case as Twig templates
  • Helps avoid duplication of code and markup in your react application
  • Code reusability across the application
  • Code Readability and maintainability
  • Have no dependencies on the rest of the app.
  • Pure functions
  • Separation of concerns
  • Style guides
  • Composition over inheritance
  • No side-effects or shared state
  • Declarative. Declarative programming for declarative library
  • Immutable state. Immutability helps avoid render errors
  • Easier to reason about component dependencies

Let’s go through the following examples:

Examples 1 : ClickCounter Component

Example 2 : Form Component

In the above example, the <button> tag exists twice. One <button> exists in the ClickCounter component, and the other in the Form component. However, both buttons do similar things.

The next example uses the react Presentation component pattern. Rather than creating multiple buttons with similar features. You convert the <ul> tag that displays a list of names into a presentation component. And do the same for the button tag. Something like this:

Create a Button component with a click functionality.

Create a person component that displays a list of names..

These are what presentational components look like. The <button> and <ul> tags are converted into separate components. And receives props from the parent component.

It describes a pattern in React that’s concerned with how things work. It's more like the business logic of an application. It manages the states; it renders the presentational component as a child component and passes state as a child props.

The following best describes the container component.

  • How things work
  • Render presentational and container components
  • Provide data and behavior

As stated above, the container component manages the states of the application and renders the presentational component as a child component. The next example uses the presentational components alongside the container components.

Both are presentational components.

The initial clickCounter and Form components do not flow with the react pattern. Because these components manage the states and render the data on the page. But, changes are made in the next example.

The following examples separate all components into two main buckets (presentational and container) components and use both together.

1. ClickCounter Container Component

The ClickCounter container component manages its own states of the application. It renders the Button component as a child component. And passes the addCounter() function as a child props to the Button component.

2. Form Container Component

The Form container component manages its own state. It renders the Button and Person presentational components as children components. The Person presentational components receive the namesList states as props from the parent container component ( Form ). The same goes for the Button as it receives the onSave() function as a prop.

The above code seems easier to read, manage, and reusable. Because the presentational handles the look of things. While the container manages the application.

This react pattern helps to structure your application. And also for better folder management. You section your folder into two parts. The presentational components; are components that handle the looks of the application. And the container components; are components that manage the state of the application.

In conclusion, this is a straightforward approach that teaches the Presentational and Container component patterns in React, and their uses. As stated above, You now know how the presentation component helps in rendering information on the page. And how the container component manages the state of the application. By now, you should know how to implement the presentational and container component pattern in your application.

Understanding the Container Component Pattern with React Hooks

Tapas Adhikary

Jan 14, 2022 · 7 min read

Understanding the Container Component Pattern with React Hooks

The modern web development era offers a plethora of libraries and frameworks. These libraries and frameworks aim to help in rapid application development, better managing source code, speed and performance of the app, and many more.

React (aka React.js and Reactjs) is a JavaScript library that helps in building interactive user interfaces keeping the following aspects in perspective,

  • The developer focuses on the states of the application and can develop a view for each of the states .
  • The developer can create components to manage the states. It allows separating the presentational part from the complex business logic.
  • Virtual DOM usage helps create an in-memory cache to detect and compute the changes, and selectively update the DOM instead of performing a complete re-render. It helps in speed and performance.

While the library provides many useful features, developers need to know how to apply the solution to the well-known problems. Over the years, React developers have solved the problem of clean code , re-usability , and keeping things simple. All these solutions evolved as patterns . In this article, we will discuss a helpful and widely used pattern in React: Container Component pattern.

The Container Component Pattern

The Container Component pattern(or simply Component pattern) ensures to separate the data fetching logic, managing state from the presentational part. The presentational part has got a dumb name, dumb component . It is because the responsibility of the presentational part is just to render the information passed to it. The smart work of data fetching, working on it, and state management occurs elsewhere.

Container Component Pattern

Traditionally, we used JavaScript classes to create containers. With the advent of hooks in React, the developer community has moved towards function-based components. We will take an example to understand the Container Component pattern end to end using React hooks.

The Movie App

We will build a movie app to fetch the movie information using an API call. We will create the user interface to show the movie details upon receiving the information.

Inslallation and Setup

Please use the Create React App tool to create an application. Let’s call it movie-app .

Please note, You’ll need to have Node version >= 14.0.0 to run the above command successfully. Once done, please perform the following steps to run the app locally.

Change to the project directory

Run the app

You can also use yarn

You should get the app running @ http://localhost:3000/

For simplicity, we will keep the movie data in a JSON file. You can also use an actual movie API to fetch the information.

Please create a data folder under the src folder. Now create a file called movies.js file with the following content,

This is a list of movies to use as an example. Please feel free to update it based on your choices.

The Movie Container

Now create a movies folder under the src folder. We will keep all the movies-app related source files under this folder.

Create a file MovieContainer.js under the movies folder with the following content,

Let’s understand what is in the above code. It is a simple React functional component.

  • We first import the movies data to use it.
  • The fetchMovies method pretends to create an abstraction to get the data from a store. In our case, it is JSON coming from a file.
  • We define the functional component MovieContainer . It logs the movies information on the browser console. It also renders a heading in the browser.
  • Finally, we export the component to import and use it elsewhere.

We will now use this component in the App.js file so that any changes we make in it reflect immediately in the UI. Please open the App.js and replace the content of it with the following code,

Here we import the MovieContainer and render it. Please visit the app in the browser. You should see the heading Movie Container to confirm our changes are working so far!

heading

Also, if you observe the browser’s console, you will find the movies JSON data logged there.

log

Let’s now show the movies information in the UI.

Showing the Movie Information

Next, we will use the movies data to construct the user interface that will show the movie information. We will leverage React Hooks to manage the state and lifecycle using functional components.

React Hooks are a great addition to the library that allows managing state and many other features without writing JavaScript classes. You can read about the motivation of introducing hooks in React from here .

For the movie-app , we will use two built-in React hooks.

useState : It helps in managing the local state so that React can preserve and use the state between re-renders. The useState hook returns the current state value and a function to update the state value. We can also pass the initial state value as a parameter to the useState() hook.

Learn more about this hook from here .

useEffect : The useEffect hook helps in performing side-effects. The side-effect can be anything responsible for changing the state of your application. A typical example of a side-effect is making an API call and changing the local state to preserve the response data.

Let us get back to the movies-app with everything we have learned about the above hooks. Move over to the MovieContainer.js file and import the useState and useEffect hooks.

Next, we will create a local state using the useState hook. Please add the following line in the MovieContainer component function.

Here we create a local state called movies initialized with an empty array([]). The setMovies is a method to update the movie’s information. We will do that as a side-effect inside the useEffect hook.

Please add the following code snippet after the useState code you have added previously.

Here we are getting the movies data(from the JSON) and updating the state (movies) using the setMovies() method. A couple of things to note here,

  • The fetchMovies() method is an abstraction. Here we are fetching the local JSON data. We can change the method’s logic to fetch it from an actual API.
  • The empty array([]) we pass to useEffect hook to inform React about calling the side-effect only once when the component loads. The effect doesn’t depend on any states to re-run again in the future.

Now let us show the movies data in the UI. To do that, please use the following JSX code in the return.

Great!!! Now our movie-app should render the movies data.

We see the data in the UI but the look-and-feel is not that great. Let us add some CSS to fix that. Please create file called movies.css under src/movies folder with the following content.

The final thing is to import the movies.css file into the MovieContainer.js file

Bingo!!! The movie-app UI looks much better now.

Here is the complete code of the MovieContainer.js file so far.

All the code we have written so far helps us show the movie information in the UI. We have accomplished our goal, but we have plenty of room for improvement.

  • First, we have the data fetching and the presentation code mixed together. It means, if we want to use the same presentation logic elsewhere, we have to repeat it. We need to avoid this.
  • Can we make the data fetching logic a bit more abstract so that any presentation can use this data in various formats?

We will use the Container Component pattern to make the first improvement. We will discuss the second improvement when discussing the Higher-Order component pattern in a future article.

The Container Component Pattern Kicks in

We separate the data fetching logic from the presentational logic with the Container Component pattern. We create as many dumb presentational components as required and pass data to them. Let’s apply this pattern to the movie-app .

The core presentation logic of the movie-app iterates through the movie information and creates UI elements for each movie. We can create a new presentation (dumb) component called Movie and pass each movie information.

Please create a file called Movie.js under the src/movies folder with the following content,

This presentational component takes the details of each movie as props and uses the values to create the UI presentations. Now we will use the Movie component into the MovieContainer component.

First, import the Movie component at the top section of the MovieContainer component.

Now replace the <li>...</li> section of the MovieContainer.js file with the following code,

That’s all. Now the MovieContainer component is much smaller than before. We have also separated out the presentation logic from the data fetching part. After the changes, here is the complete code of the MovieComponent.js file.

If we see it in a pictorial representation, it may look like this:

one level

Do you think we should refactor the code a bit more to create another parent-level presentation component? Well, we can. We can create a presentation component called MovieList (taking the <ul>...</ul> part), and that can use the Movie Component. Finally, we can use the MovieList component in the MovieContainer . It may look like this:

two level

It all depends on how far you think you should go keeping the re-usability and separation of concern in mind. I hope we understand the idea behind the Container Component pattern.

Open Source Session Replay

OpenReplay is an open-source, session replay suite that lets you see what users do on your web app, helping you troubleshoot issues faster. OpenReplay is self-hosted for full control over your data.

replayer.png

Start enjoying your debugging experience - start using OpenReplay for free .

As we mentioned before, the patterns are evolved from the solution of repeated problems in the past. You can choose to adopt, tweak, or even not use it.

A pattern such as Container Component pattern helps in achieving the principles of,

  • Separation of Concern(SoC) by keeping the data fetching and presentation away from each other.
  • Don’t Repeat Yourself(DRY) by providing us the ability to reuse a component multiple times in different places.

Like this one, we have other patterns like Higher-Order Component(HoC) pattern, Render Props, and many more. We will see them soon in the upcoming articles. Stay tuned.

You can find all the source code used in this article from here,

The movie-app project on GitHUb

Before we end…

I hope you found this article insightful and informative. My DMs are open on Twitter if you want to discuss further.

Let’s connect. I share my learnings on JavaScript, Web Development, and Blogging on these platforms as well:

Follow me on Twitter

Subscribe to my YouTube Channel

Side projects on GitHub

More articles from OpenReplay Blog

The best extensions for using Git with VSCode

Apr 12, 2023, 4 min read

Top Visual Studio Code extensions for Git

{post.frontmatter.excerpt}

Better ways of working with Svelte and VSCode

Mar 3, 2023, 4 min read

Top Visual Studio Code extensions for Svelte developers

  • React Native
  • CSS Frameworks
  • JS Frameworks
  • Web Development
  • React Tutorial
  • React Introduction
  • React Environment Setup

React Fundamentals

  • ReactJS Babel Introduction
  • ReactJS Virtual DOM
  • React JS ReactDOM
  • React Lists
  • React Forms
  • ReactJS Keys
  • ReactJS Refs
  • ReactJS Rendering Elements
  • React Conditional Rendering
  • React Components
  • Code Splitting in React
  • ReactJS | Components - Set 2
  • ReactJS Pure Components
  • ReactJS Functional Components
  • React Lifecycle
  • Differences between Functional Components and Class Components

ReactJS Container and Presentational Pattern in Components

React props & states.

  • ReactJS Methods as Props
  • ReactJS PropTypes
  • ReactJS Props - Set 1
  • ReactJS Props - Set 2
  • ReactJS Unidirectional Data Flow
  • ReactJS State
  • ReactJS State vs Props
  • Implementing State in React Components
  • React Hooks
  • React useState Hook
  • ReactJS useEffect Hook
  • Context in React
  • React Router
  • React JS Types of Routers
  • ReactJS Fragments
  • Create ToDo App using ReactJS
  • Create a Quiz App using ReactJS
  • Create a Coin Flipping App using ReactJS
  • How to create a Color-Box App using ReactJS?
  • Dice Rolling App using ReactJS
  • Guess the number with React

React Connection & Deployment

  • How to Deploy Your React Websites on GitHub?
  • How to Deploy React project on Firebase?
  • How to deploy React app to Heroku?
  • How to deploy React app to Surge ?
  • How to deploy simple frontend server-less (static) React applications on Netlify

React Exercises

  • React Exercises, Practice Questions and Solutions

React Questions

  • How to connect Django with Reactjs ?
  • 7 React Best Practices Every Web Developer Should Follow
  • 8 Ways to Style React Components
  • How to add Stateful component without constructor class in React?
  • How to display a PDF as an image in React app using URL?
  • React JS Toast Notification
  • What is the use of data-reactid attribute in HTML ?
  • How to zoom-in and zoom-out image using ReactJS?
  • How to avoid binding by using arrow functions in callbacks in ReactJS?
  • How to bind 'this' keyword to resolve classical error message 'state of undefined' in React?
  • How to get the height and width of an Image using ReactJS?
  • How to handle multiple input field in react form with a single function?
  • How to handle states of mutable data types?
  • How to change state continuously after a certain amount of time in React?
  • How to change the state of react component on click?

In this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern.

Presentational and Container Components

The type of components is decided by components pattern. If the component decides how the data will be presented on the screen it is called as presentational component . If the component focuses on what data is to be shown to the user then it is called as container component

We will discuss individually about these components in this article.

Presentational components:

  • Mainly concerned with how things look.
  • Have no major dependencies on the rest of the app.
  • No connection with the specification of the data that is outside the component.
  • Mainly receives data and callbacks exclusively via props.
  • May contain both presentational and container components inside it considering the fact that it contains DOM markup and styles of their own.

Example: For example, the below code denotes a presentational component, and it gets its data from the props and just focuses on showing an element. 

Container components:

  • Mainly concerned with how things work.
  • May contain both presentational and container components but does not have DOM and markup of their own.
  • Provide the data and behavior to presentational or other container components.
  • Call flux actions and provides these as callbacks to the presentational component.

Benefits of Container/Presentational Pattern

  • Creates pure functions
  • Separates render and fetching logic
  • Makes the components more reusable
  • Testing the components is easier

Disadvantages of Container/Presentational Pattern

  • It’s alternatives perform better
  • Usage is decreased as we no longer need class components to create states.

Alternative to Presentational/Container Pattern

This pattern based approach can be easily replaced with using hooks in React. Instead, of creating different components based on the pattern we can create a single component which uses hooks to implement different functionality. Since the introduction of hooks in React the use of this pattern is reduced but it is still used in some cases as performing tests is easier in this pattern approach.

author

Please Login to comment...

Similar reads.

  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

presentation component pattern

Angular Architecture - Container vs Presentational Components Common Design Pitfalls

Angular University

Angular University

High-Quality Angular Courses

More posts by Angular University.

This post is part of the ongoing Angular Architecture series, where we cover common design problems and solutions at the level of the View Layer and the Service layer. Here is the full series:

  • View Layer Architecture - Smart Components vs Presentational Components
  • View Layer Architecture - Container vs Presentational Components Common Pitfalls
  • Service Layer Architecture - How to build Angular apps using Observable Data Services
  • Service Layer Architecture - Redux and Ngrx Store - When to Use a Store And Why?
  • Service Layer Architecture - Ngrx Store - An Architecture Guide

Let's then talk a bit about Angular Component Architecture: We are going to present a very common component design and a potential design issue that you might run into while applying it.

A Common Component Design (And a potential issue with it)

A really important aspect of Angular application development is application component design: How to combine different types of components together, when to use a component vs a directive, how and when to extract functionality from components into directives, etc.

Angular Components provide a lot of functionality that can be used and combined in many different ways. This allows us to adopt a large variety of application designs depending on the situation.

In this post, we are going to talk about one particular type of design that we often hear about.

Container Components vs Presentational Components

The design scenario that we will be talking about is the separation of components between Container Components vs Presentational Components.

This is a popular design that is now being used more and more in the Angular ecosystem since now Angular supports the Component model. The design is presented in this blog post by Dan Abramov (@dan_abramov) :

Presentational and Container Components

The post is for React but the notions apply also to any ecosystem that allows a component based design model, like Angular.

An example of the Container vs Presentational Design

So let's give a quick example of this design, please bear in mind that different terms are used to name the different types of components.

The core idea of the design is that there are different types of components. Using the same terminology as in the blog post above we have:

  • Container Components: These components know how to retrieve data from the service layer. Note that the top-level component of a route is usually a Container Component, and that is why this type of components where originally named like that
  • Presentational Components - these components simply take data as input and know how to display it on the screen. They also can emit custom events

Let's give a simple example of this design, that will actually already contain a potential design issue . To keep it more fun I suggest the following: try to spot the design issue as I present the example, and we will go over the issue later in this post.

If you have already tried to use this design, most likely you have come across this problem.

A Top-Level Component Written in Reactive Style

So let's get started with the top-level component of our route. Let's have a look at a simple route top-level component written in reactive style:

This is a simple component that presents the details of a course: in contains a header that contains a summary of the course (plus a newsletter box) and a list of lessons.

So let's break it down what we have in this top-level component and how it's currently designed:

  • the component has router dependencies injected, but also some application-specific services
  • the component does not have any variables that keep direct references to data, like lessons or courses
  • instead, the component declares a few observables on ngOnInit , that are derived from other observables obtained from the service layer

Top-Level Component Design Overview

This top-level component will define how to get the data from the service layer, based on a routing identifier parameter.

This is a typical top-level component in a reactive style application that does not use router data pre-fetching (more on this later). This component will be displayed without any data initially, and it will do one or more calls to the service layer to fetch the data.

Notice that the component is just defining a set of Observables, but no subscriptions are done in the component class: so how is the data displayed then?

The Template of The Top-Level Component

So let's now have a look at the template for this component, and see how these observables are being used:

As we can see, we are taking the observables and we are subscribing to them via the async pipe. The data then gets applied to a tree of local components that exist under the top-level component of this route:

  • multiple types of data, including the user, the lessons, and the courses are being passed to the course-detail-header component, as well as to a list of lessons.
  • These components are responsible for presenting the data retrieved by the top level component

A note on multiple subscriptions

One important thing: the lessons$ observable is being subscribed two times. In this case, it would not pose a problem because the observable coming from the service layer is designed to prevent multiple requests to the backend, for example using publishLast().refCount() .

Note that this is just one possible solution for ensuring that multiple subscriptions are not a problem. So let's have a look now at one of these local components that are being used in the top-level component template. We will see that they have a very different design.

Looking into the design of a Presentational Component

So the top-level component is a container component, but what about the other components that used in the template?

Presentational components will take care of taking input data and presenting it to the user. So for example, the course-detail-header is a presentational component. Let's have a look at what this component looks like:

Reminder: try to spot the issue with this design

As we can see, the component takes as input some data that then gets rendered to the screen. This component does not have dependencies with the service layer of the application, instead, it receives its data via inputs.

It also emits outputs, such as for example the subscribe output event. But where is this event coming from? We can see that is being triggered in response to an event with the same name coming from the newsletter component.

And what does the newsletter component look like, how is it designed? Let's have a look.

A Presentational Component one level deeper the Component Tree

The newsletter component is also a presentational component, because it takes an input, displays a subscription form and emits an event upon subscription:

So this is the design we currently have for the newsletter component, so let's review it in more detail to see what the problem could be.

A Potential issue with this design

You might have noticed a couple of things in the newsletter component that are similar to the course-detail-header component:

  • the input property first name
  • the output event subscribe

Both of these elements are repeated in the two components. So it looks like we are doing a couple of things in this design that would likely not scale well in a larger component tree, because there is a lot of repetition involved.

Let's go over these two issues and see how could we potentially design this otherwise.

Design Issue 1 - Extraneous Properties in Intermediate Components

It looks like we are passing inputs like firstName over the local component tree, in order for leaf components like the newsletter component to use them. But the intermediate components themselves are not using the inputs, they are just passing them to their child components.

Usually, the local component tree is much larger than this example, so this issue would potentially result in a lot of repetition of inputs.

Also and more importantly: if we are using third-party widget libraries and we use some of those components as intermediate components, we might have trouble passing all the necessary data through the component tree, depending on how the libraries are designed.

There is also another similar issue, which is linked to the outputs.

Design Issue 2 - Custom Event Bubbling Over the Local Component Tree

As we can see, the subscribe event is being also repeated at multiple levels of the component tree, this is because by design custom events do not bubble.

So also here we have a code repetition problem that won't scale well for a larger example, and won't work with third-party libraries - we wouldn't be able to apply this technique in that case.

Also, the logic for subscribing to the newsletter (the call to newsletterService ) is on the top-level route component, and not on the newsletter component.

This is because only the top-level component has access to the service layer, but this ends up causing that potentially a lot of logic is kept on that component because of that.

So how can we solve these issues in Angular? Let's have a look at a possible solution.

Preventing Custom Event Bubbling

If we find ourselves in a situation where we are manually bubbling events up the component tree, that might work well for certain simpler situations. But if the event bubbling / extraneous properties start to become hard to maintain, here is an alternative.

We are going to present the alternative via a step by step refactoring. Let's start our refactoring from our top-level component again, and see how the new solution avoids the issues that we have identified.

If you would like to have a look at a video version of refactoring ver similar to this one, have a look at this video:

The refactored top-level component

Let's change the top-level component so that it no longer passes as much data or receives as many events from the local component tree. Let's also remove the newsletter subscription logic.

The new version of the top level component now has a lot less code than before:

So this looks like a good start. And what about the top-level component template ? The new template is mostly identical after the refactoring, except for the course-detail-header component:

This is looking better than the version we had before: we don't see the passing of firstName or the bubbling of the subscribe event anymore.

So what does the course-detail-header intermediate component now looks like after the refactoring?

The refactored intermediate component

We can see here that the new version of the course-detail-header component is now much simpler after the refactoring:

This new version of the component still contains the newsletter, but it no longer is bubbling events and passing data that is not needed by the component itself.

So again this looks a lot better than the version we presented initially. But where is now the functionality for subscribing to the newsletter?

Let's now have a look at the final component in this refactoring: the leaf component.

The refactored leaf component

As we can see, the newsletter leaf component is now designed in a completely different way:

So what is now the biggest design difference in this new version of the newsletter component?

The biggest difference is actually that this new version looks a lot like a Container Component!

So as we can see, sometimes the best solution is to inject services deep into the component tree. This really simplified all the multiple components involved in this example.

But this implementation of the Leaf component could be further improved, so let's review in further detail this design to see how.

Reviewing the new component design solution

The new design for this particular tree of components seems to be more maintainable. There is no longer bubbling of custom events or the passing of extraneous input properties through the component tree.

The newsletter component is now aware of the service layer and is currently getting all its data from it. It has a reference to the newsletter service, so it can call it directly. Note that this component could still receive inputs if needed, more on this later.

Leveraging Angular features to get a simpler design

We can see that in this new version of the component tree, we are now leveraging the Angular Dependency Injection system for injecting services deep in the local component tree.

This allows deeply nested components like the newsletter component to receive data from the service layer directly, instead of having to receive it via inputs.

This makes both the top-level component and the intermediate components simpler and avoids code repetition. It also allows for logic for interaction with the service layer to be put deeply into the component tree, if that is where it makes the most sense to have it.

One problem with this current implementation of the newsletter component

There is just one problem with this new version of the newsletter component: unlike the previous version which was a presentational component:

this new version will not work with OnPush change detection!

Making the newsletter component compatible with OnPush

You might have noticed before that sometimes when we switch a component to use OnPush change detection, things stop working - even if we are not doing local mutation of data at the level of the component.

And one example of that would be the current version of the newsletter component, which indeed would not reflect new versions of the first name on the template.

But here is a version of the component that is compatible with OnPush as well:

So what is the difference with this new implementation? In this version of the component, we have defined a first name observable, and we have consumed it in the template using the async pipe.

The use of the async pipe will ensure that the component will be re-rendered when a new version of the first name is emitted (for example when the user logs in), even if the component has no inputs - because the async pipe will detect that a new value was emitted by the observable and so it will then mark the component for re-rendering.

Conclusions

So as we can see there are many possible component designs, depending on the situation. Using the Angular Dependency Injection system really makes it simple to inject services deep in the component tree if we need to.

So we don't necessarily have to pass data and events through several levels of the component tree, as that might cause maintainability problems due to code repetition (among other problems).

But then why does this end up happening so often while trying to apply the Container + Presentational design?

A possible explanation for the custom event bubbling problem

There is one likely main reason why this design might end up being used: in software design the names we give things can have a lot of impact.

And the name Container Components makes us think that only the top-level component of the route should have that type of design and that all other components used by it should then be presentational, which is not the case.

The name Container does not make us think of a leaf component like the newsletter component.

So to avoid this issue, here is a suggestion: If we need to give a name to components that are aware of the service layer, and having a name helps in application design discussions, we could call them for example something like Smart Components instead, and reserve the term Container to the top-level component of the route only.

In practice its actually much more practical to mix and match the multiple types of component design as we need, and use different types of components at different levels of the tree as necessary - mixing the different features as much as we need.

I hope that you enjoyed the post and that it helped getting started with view layer design. We invite you to subscribe to our newsletter to get notified when more posts like this come out:

And if you are looking to learn more about more Angular application design patterns, we recommend the Reactive Angular Course , where we cover lots of commonly used reactive design patterns for building Angular applications.

If you are just getting started learning Angular, have a look at the Angular for Beginners Course :

presentation component pattern

Other posts on Angular

If you enjoyed this post, have also a look also at other popular posts that you might find interesting:

  • Angular Smart Components vs Presentation Components: What's the Difference, When to Use Each and Why?
  • Angular Router - How To Build a Navigation Menu with Bootstrap 4 and Nested Routes
  • Angular Router - Extended Guided Tour, Avoid Common Pitfalls
  • Angular Components - The Fundamentals
  • How to build Angular apps using Observable Data Services - Pitfalls to avoid
  • Introduction to Angular Forms - Template Driven vs Model Driven
  • Angular ngFor - Learn all Features including trackBy, why is it not only for Arrays ?
  • Angular Universal In Practice - How to build SEO Friendly Single Page Apps with Angular
  • How does Angular Change Detection Really Work ?
  • Angular. Container and presentational components (aka smart-dumb)

Hi! Today I would like to talk about one of the most important architectural patterns in Angular.

The pattern itself is not related to Angular directly, but as Angular is component-driven framework, this pattern is one of the most essential for building modern Angular applications.

Container-Presentation pattern

It is believed that good components should be small, focused, independent, testable and most important - reusable.

If your component is making server calls, contains business logic, tightly coupled to other components, knows too much about other component’s or services’ internals, then it become bigger, harder to test, harder to extend, harder to reuse and harder to modify. To solve these problems the pattern “Container-Presentation” exists.

Generally, all the components can be divided in two groups: Container (smart) and Presentational (dumb) components.

Container components can get data from services (but should not call server APIs directly), contain some business-logic and serve data to services or children components. Usually, container components are those we specify as routed components in our routing configuration (but not always, of course).

Presentational components must only take data as input and display it on the screen in some way. They can react on user inputs, but only by changing its local isolated state. All the communications with the rest of the app should be done by emitting custom events. These components should be highly reusable.

For better context I will name some examples of container and presentational components:

Container: AboutPage, UserPage, AdminPanel, OrderPage, etc.

Presentational: Button, Calendar, Table, ModalDialog, TabView, etc.

Example of a crazy button

Let’s look at extremely bad example of misusing the components approach I faced myself in one of the real projects.

I simplified it for better readability, but in reality things was much worse. This is a button component which contains all of the possible actions user can invoke by clicking button – making API calls, validating forms, retrieving information from the services and more. You can imagine how fast such component can become a hell in even relatively small application. The code of such button component I found (and then refactored) was more than 2000 lines long. Insane!

When I asked the developer who wrote it, why he decided to put all of this logic in the single component, he said that this is “encapsulation” 🙀

Let’s remember what qualities good components should have:

Small - this button with 2000+ lines of code isn’t small. And it will become bigger every time someone will need another button for different action.

Focused - this button do a lot of absolutely unrelated things and can’t be called focused.

Independent - this button is tightly coupled with several services and forms, and changing any of them will affect the button.

Testable - no comments.

Reusable - it is not reusable at all. You need to modify component’s code every time you want to use it for action it doesn’t have, and you will get all the unneeded actions and dependencies this button has.

Moreover, this button component hides native HTML button under the hood, blocking access to its properties for developer. This is a good example of how component should not be written.

Let’s put some very simple example of component which uses this button component and then will try to refactor them with Container-Presentation pattern.

You can see that there is no logic inside this component – the form stored in a service, and the button contains all the logic invoking by click on it. So our button now have all the logic unrelated to its behavior, and smarter than its parent component which is directly related to the actions processed by button.

Refactor button component with Container-Presentation pattern

Let’s separate the functions of these two components. Button should be presentational component – small and reusable. Registration form which contains the button can be container component which will hold business logic and communications with services layer.

We will not cover the part with unhiding the native button (I will probably cover this in some future article), but will focus mainly on architectural aspect of relation between these two components.

Refactored button component (presentational)

As you see, our refactored button is very simple. It has only two Inputs and one Output. Inputs are used for taking data from parent component and display it to user (modify button look with classes and display button label). Output is used for custom event which will be fired every time user click our button.

This component is small, focused, independent, testable and reusable. It does not contain any logic unrelated to behavior of the component itself. It has no idea of internals of rest of the application and can be safely imported and used in any part of the application or even in the other applications.

Refactored registration form component (container)

You can see that our registration form now uses button and reacts on its click event with calling registerUser method. The logic of this method is tightly related to this form, so it is good place to put it here.

This was pretty simple example and we have only two levels in the component tree. There are some pitfalls with this pattern when you have more levels in your component tree.

More sophisticated example

This is not a real world example, but I hope it will help to understand possible issues with this pattern.

Imagine we have such component tree (from top to bottom):

user-orders - top-level component. It is container component which talks to services layer, receives data about user and their orders, passes it further the tree and renders the list of the orders.

user-orders-summary - middle level component. It is presentational component which renders the bar above the user orders list with total number of orders.

cashback - bottom level (leaf) component. It is presentational component which displays the total amount of user’s cashback and has a button to withdraw it to bank account.

Top-level container component

Let’s look on our top-level user-orders container component.

As you can see, user-orders component defines two observables: user$ and orders$ , using async pipe in template to subscribe to them. It passes the data to presentational component user-orders-summary and also renders a list of orders. Also it talks to service layer reacting on custom event requestCashbackWithdrawal emitted from user-orders-summary .

Middle level presentational component

This component is designed very similarly to our refactored button component. It renders the data received through its inputs and emits custom event on some user action. It does not call any services and does not contain any business logic. So this is the pure presentational component which uses another presentational cashback component.

Bottom level presentational component

This is another presentational component which only receives the data through input and throw events with output. Pretty simple and reusable, but we have some problems in our component tree .

You probably noticed that user-orders-summary component and cashback component have similar Inputs ( cashbackBalanace and balance ) and same Output ( requestCashbackWithdrawal ). That’s because our container component is too far from deepest presentational component. And the more tree levels we will have with this design, the worse the problem will become. Let’s look at this problems closer.

Issue 1 - Extraneous properties in middle level presentational components

Our user-orders-summary receives cashbackBalanace Input just to pass it further down the tree but not even use it by itself. If you face such situation, this is one of the markers that you probably may have component tree design flaw. Real life components may have a lot of inputs and outputs, and with this design you will have a lot of “proxy” inputs which will make your middle level components less reusable (as you tight them to children components) and a lot of repeatable code.

Issue 2 - Custom event bubbling from down to top-level components

This issue is very similar to previous one, but related to component’s outputs. As you can see, requestCashbackWithdrawal custom event is repeated in cashback and user-orders-summary components. That again happens because our container component is too far in the tree from the deepest presentational component. And it also makes our middle component non-reusable by itself.

There are at least two possible solutions to this problems.

1st – make your middle level components more content agnostic using ngTemplateOutlet and expose your deeper components to container components directly. We will pass this for today as it deserves separate article.

2nd – redesign your component tree.

Refactoring our component tree

Let’s refactor our code to see how we can solve the problems with extraneous properties and event bubbling in middle level component.

Refactored top-level component

We removed the user$ observable and onRequestCashbackWithdrawal() method from our top-level container component. It is much simpler now and passes only the data needed to render user-orders-summary component itself, but not its child cashback component.

Middle level refactored component

It is also simplified a lot. Now it only has one Input and renders the total number of orders.

Bottom level refactored component

Wow. As you can see, it is not presentational anymore . Now it looks very similar to our top-level component, so it is container component down the component tree. This refactoring allowed us to simplify the whole component tree design and APIs and logic of our two components up the component tree.

What about reusability of our new cashback component? It is still reusable, as it contains only the logic related to the component itself, so it is still independent.

The new design of our component tree seems to be more maintainable, more streamlined and more atomized. We have no bubbling events now, we have no repeatable inputs through the component tree and overall design is much simpler. We achieved this by putting additional container component down the component tree. This method can be used to simplify your component tree design, but you should have good understanding which components in your tree are suitable for being containers without big loss in reusability, and which should be pure presentational components. That’s always a subject of balance and design choices when you create your app’s architecture.

It’s very easy to misunderstand the Container-Presentation pattern and think that container components can only be top-level components (intuitively, they contain all the other components in the local component tree). But this is not the case, container components can be on any level of the component tree, and as you saw, even on the leaf level. I like to call them smart components because for me it’s much clear that these components will contain some business logic and can be presented anywhere in the component tree.

I hope at this moment you have better overview on Container-Presentation pattern and possible issues with its implementation.

I tried to keep it as simple as possible, but there is a ton of information available related to this pattern.

If you have any questions or notes, feel free to reach me in the comments.

The next article will be about changeDetectionStrategy in Angular (which is highly related to this post).

  • What's new in Angular 14
  • Angular. General tips

Log in or sign up

Log in or create a new account to continue

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Regarding Dan Abramov's update about Presentational and Container Components, and hooks [closed]

Presentational/Container components are known as a good separation of concerns pattern in React, and if we search about the topic you'll definitely find Dan Abramov's post regarding that.

But quite some time ago he then updated that post with a statement that can be interpreted that due to the recent adaptability to using Hooks, the presentational/container components pattern is not as recommended as it was before. Since we can create custom hooks that contain that code instead.

How do you interpret what he meant by that?

Having a gigantic custom hook that does all that logic and returns a bunch of variables? And then calling that hook in a component?

Personally I still find container components useful as it separates what is business logic (calling apis and handling the result flow of that) from "UI logic" (storing state for a tab, an animation)

It's easier when you're working with a large scale app to find where the API, redux or graphql calls are being done if they're in its own place, and always following the same pattern. But if we didn't have that, how would we solve this problem and not having a mess of multiple components calling apis and doing its own thing everywhere in the app/tree?

I'm asking this because even when still using container components to only fetch an api and/or get the redux state, and keeping everything tidy, sometimes I still find useful for some components to call the API and do what a "container" would do themselves, to avoid having to pass down props or making a container TOO big/confusing. And it is kind of conflicting having just some components do that and the rest stay in a container component. How would you handle that?

  • react-hooks

assisrMatheus's user avatar

I think presentational components pattern is still relevant with hooks. You can still use the main logic in "Container" component, but in case of hooks, you can remove the concern of using not relevant state from the "Container" component.

For example, you have a list component that directs the main logic and each item has a drop-down in it, is drop-down shown or not is not relevant for the whole list, so its state should stay in the presentational component.

Also, custom hooks are just functions that allow you to re-use state and lifecycle features, so it has no relation to the pattern.

Beso Kakulia's user avatar

Not the answer you're looking for? Browse other questions tagged reactjs react-hooks or ask your own question .

  • Featured on Meta
  • We spent a sprint addressing your requests — here’s how it went
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Is it a security issue to expose PII on any publically accessible URL?
  • Can I give a potential employer the LinkedIn address of my previous employer instead of his email address?
  • Book read in the 80/90s about an alien microbe taking over creatures
  • Error concerning projectile motion in respected textbook?
  • Does the oven temperature for a lasagna really matter?
  • Confusion regarding "since" vs "for"
  • Switching Tenure-Track Positions Within Same University
  • Can IBM Quantum hardware handle any CSWAP at all?
  • Coping with consequences of a dog bite before buying a puppy
  • bpy.app.timers.register is lagging Blender
  • Is this a Hadamard matrix?
  • I am trying to calculate Albumin-Creatinine ratios for research, why is the result so high?
  • Does 誰と mean 誰とも?
  • What's the most accurate translation for "Comic Convention"?
  • Car stalls when coming to a stop except when in neutral
  • What do American people call the classes that students go to after school for SATs?
  • Why is this outlet required to be installed on at least 10 meters of wire?
  • Which interpreter for "Unicode text, UTF-8 text executable"
  • Unable to use split. tryed doing with align got more error in that also due to this im unable to fit the equation the page
  • Could a Black Market exist in a cashless society (digital currency)?
  • Why do "dual frequency" or low frequency switching regulators exist when higher frequency is better?
  • Using grout that had hardened in the bag
  • Implementation of Euler-Maruyama numerical solver
  • How does light beyond the visible spectrum relate to color theory?

presentation component pattern

News & Events

Capstone awards showcase top work.

Amy Sprague July 1, 2024

We recognize outstanding capstone projects in design, innovation and film excellence from graduating seniors.

We are excited to announce our 2024 capstone award winners. Through an intense, year-long process, the student teams tackled complex, real-world design challenges sponsored by leading aerospace companies, our faculty and student organizations. Their innovative solutions demonstrated remarkable creativity, technical mastery, and commitment to excellence.

Technical Awards

Group of people posing behind a remote controlled aircraft

The DBF Air Cargo Challenge capstone team with their plane at the Undergraduate Showcase: Leon Betancourt, Osvaldo Aldaz, Aakash Bansal, Peter Funston, Enoch Kwong, Evelyn Madewell, Jevoni Sykes, Kas Bakker. Missing: Kayden Greenup.

Technical Excellence: Design Build Fly Air Cargo Challenge

Team: evelyn madewell, leon betancourt, enoch kwong, kas bakker, kayden greenup, peter funston, jevoni sykes, osvaldo aldaz, aakash bansal.

This team delivered excellent work by applying fundamental principles and following the systems engineering process to successfully test a stable airplane through several flights. Their thorough analysis and design work was complemented by well-developed manufacturing plans, resulting in a high-quality vehicle specifically designed with very small performance margins to be a strong competitor in the upcoming challenge.

Innovation: SPACE Lab Pulsed Plasma Thruster (PPT) Balance

Team: nathan cheng, felicity cundiff, adam delbow, ben fetters, lillie laplace, kai laslett-vigil, winston wilhere.

This team was challenged to push the limits of previous measurement systems for PPTs with very small thrust. While the inverted pendulum balance design has been used in the past, they faced the challenge of making one that the customer (SPACE Lab) knew had exceptional ranges—from 10 micro-Newtons to 100 milli-Newtons. The challenge was further heightened by requiring a system that could safely operate inside a vacuum chamber with minimal metal components. Although the full range was not achieved, the team's design pushed the limits of what a PPT Thrust Balance can accomplish and paved the way for a future version to achieve the main objective.

Left: A group of people stands in a lab with scientific equipment in the back. Right: Two people interact with an device on a table during an expo.

Left: The SPACE Lab capstone team: Nathan Cheng, Ben Fetters, Lillie LaPlace, Kai Laslett-Vigil, Adam Delbow, Winston Wilhere, Felicity Cundiff, with Professor Justin Little. Right: The SPACE Lab team’s pulsed plasma thruster balance model.

Film Fest Awards

Best in show: fly and swim drone, team: angelina dos remedios, thomas george, nolan klissus, lucas lestenkof, tony mcdaniel, allie surprise, william (aarron) watts.

This team designed a dual-medium amphibious drone capable of maintaining a flight time of at least 15 minutes and a swim time of at least 20 minutes, reaching an airspeed of 45 miles per hour and a swim speed of at least three mph at a depth of up to four feet.

Honorable Mention: Boeing Regional Airline

Team: grayson atwell, jason cundrawijaya, salomé demurger, salvador hernandez, mack howard, aaron hsu, alex zhang.

This team created a preliminary design for Boeing of a 75-passenger regional jet that would have 20 percent better fuel burn than comparable jets and would fly a minimum range of 1500 nautical miles while running on sustainable aviation fuel.

People’s Choice: Lockheed Martin Lunar E-Launch

Team: yaffet bedru, justin danh, ethan duer, sydney jackson, kyle klem, haili kuester, phuong le, daniel lord, kevin major, katelynn moen, julius naehrig, emi peterson, cesar tirado.

This team proposed a lunar electromagnetic launch system and built and tested a sub-scale launcher to launch payloads from the surface of the Moon.

View the entire 2024 Capstone Film Fest

A&A's talented capstone teams have crafted 3-minute videos showcasing their amazing work.

presentation component pattern

Cooking up a great prompt: Getting the most from Copilot

Prompts are how you ask Copilot for Microsoft 365 to do something for you — like creating, summarizing, editing, or transforming. Think about prompting like having a conversation, using plain but clear language and providing context like you would with an assistant.

1. Tell Copilot what you need

"Give me a concise summary of recent news about [Product X]."

“Write a session abstract of this /[presentation].”

“Check this product launch rationale for inconsistencies.”

"Create a value proposition for [Product X].”

“Create an onboarding presentation based on this /[document].”

"What's the latest on [Project X].”

2. Include the right prompt ingredients

To get the best response, it’s important to focus on some of the key elements below when phrasing your Copilot prompts.

An infographic showing the four elements of a great prompt: Goal, Context, Source, and Expectations.

3. Keep the conversation going

Following up on your prompts help you collaborate with Copilot to gain more useful, tailored responses.

Lead with broader requests, then give specific details about the content.

Ask for a summary of a specific file, then ask relevant questions to gain deeper insights.

Request a meeting recap, then ask for more information about what you should know​.

Ask Copilot to translate a sentence to one of the supported languages, then ask for more context or a regional dialect.

Ask Copilot to write a story, then guide it by giving more specific, relevant details​.

Present a technical problem, then narrow it down, or ask for step-by-step guidance.

Helpful hints to keep in mind

Know Copilot’s limitations  Copilot is limited to your current conversation, so give lots of details.

Be professional Using polite language improves Copilot’s response.

Communicate clearly Pay attention to punctuation, grammar, and capitalization.

Use quotation marks ​​​​This helps Copilot know what to write, modify, or replace for you.

Start fresh Avoid interrupting and type “new topic” when switching tasks.

Copilot Lab

Facebook

Need more help?

Want more options.

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

presentation component pattern

Microsoft 365 subscription benefits

presentation component pattern

Microsoft 365 training

presentation component pattern

Microsoft security

presentation component pattern

Accessibility center

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

presentation component pattern

Ask the Microsoft Community

presentation component pattern

Microsoft Tech Community

presentation component pattern

Windows Insiders

Microsoft 365 Insiders

Was this information helpful?

Thank you for your feedback.

IMAGES

  1. Simple 4-Component Slide Template with Core Element for PowerPoint

    presentation component pattern

  2. Simple 4-Component Slide Template with Core Element for PowerPoint

    presentation component pattern

  3. Container vs. Presentation Components

    presentation component pattern

  4. Modern Professional PowerPoint Template

    presentation component pattern

  5. 7-Step Component Diagram for PowerPoint

    presentation component pattern

  6. 15 Stunning Geometric Patterns You Can Create in PowerPoint for

    presentation component pattern

VIDEO

  1. Patterns and Frameworks for Service Configuration and Activation (Part 1)

  2. Developing Personal Skills Presentation (Component 2)

  3. Linear component pattern in solidworks assembly

  4. Intro to Angular

  5. Pattern Driven Component Pattern in SolidWorks Assembly

  6. 5 Patterns for Better Components in Vue.js

COMMENTS

  1. Container/Presentational Pattern

    Composables. Do read the Composables guide for a deep-dive into understanding composables.. In many cases, the container/presentational pattern can be replaced with composables. The introduction of composables made it easy for developers to add statefulness without needing a container component to provide that state.. Instead of having the data fetching logic in the DogImagesContainer ...

  2. Presentational and Container Components

    Provide the data and behavior to presentational or other container components. Call Flux actions and provide these as callbacks to the presentational components. Are often stateful, as they tend ...

  3. Container/Presentational Pattern

    The Container/Presentational pattern encourages the separation of concerns. Presentational components can be pure functions which are responsible for the UI, whereas container components are responsible for the state and data of the application. This makes it easy to enforce the separation of concerns.

  4. Separation of Concerns in React -How to Use Container and

    To solve this and to adhere to the separation of concerns, we should separate these two pieces of logic - that is, fetching data and presenting it on the UI - into two different components. This is were the container and presentation component pattern will help us solve this issue. In the following sections, we are going to dive deep into ...

  5. Angular Design Patterns: Feature and Presentation Components

    This article has been updated to the latest version Angular 17 and tested with Angular 16. The content is likely still applicable for all Angular 2 + versions. In this post, we will cover the Feature and Presentation Component Design pattern. This pattern has been called many things such as. Smart/Dumb Components. Stateful/Stateless Components.

  6. Mastering React Patterns: Presentational and Container Components

    Introduction: In the world of React development, understanding patterns and best practices is crucial for building robust and maintainable applications. One essential pattern is the separation of components into Presentational and Container components. In this article, we will delve into the concepts of Presentational and Container components, explore their benefits, and provide real-world ...

  7. Angular Smart Components vs Presentational Components

    This post is part of the ongoing Angular Architecture series, where we cover common design problems and solutions at the level of the View Layer and the Service layer. Here is the full series: * View Layer Architecture - Smart Components vs Presentational Components * View Layer Architecture - Container vs Presentational

  8. React Design Patterns: The Container/Presentational Pattern

    Jul 28, 2023. 1. Photo by Hal Gatewood on Unsplash. The Container/Presentational pattern, also known as the Container/View pattern or the Smart/Dumb pattern, is a design pattern commonly used in ...

  9. React: Intro to the page, container and presentation component pattern

    At its core, this pattern is a symphony of separation, where each component plays a distinct and crucial role: Page Components serve as the conductors, orchestrating the layout and flow of the pages.

  10. An Overview of Presentational and Container Component Pattern

    As you study other React applications and work on different React applications built with different teams, you notice some common design patterns. Let's take a look at a popular design pattern for building React applications, you are gonna love it. Presentation Components. The look and feel of the UI depends on these components.

  11. An Intro to Container-Presenter Design Patterns in React

    The philosophy behind the Container-Presenter design pattern is rather simple; components are split up into 2 categories based on a couple of loosely-defined factors: ... Presentation Components. Characteristics: Are concerned with how things look. Depend exclusively on passed down data & callbacks (via props)

  12. Presentational and container components · React in patterns

    However, there is a pattern which is used widely and helps organizing React based applications - splitting the component into presentation and container. Let's start with a simple example that illustrates the problem and then split the component into container and presentation. We will use a Clock component.

  13. Container/Presentation Pattern

    Here's what you'd learn in this lesson: Lydia explains how the container presentation pattern enforces a separation of concerns by abstracting the view from the application logic. Presentational components focus on how the data is shown to the user. Container components are responsible for the data passed to the presentational component.

  14. What Are Presentational and Container Components in React?

    The container component's. method is almost identical to that in the presentational component. The difference is the container component sources its text from inside itself, instead of relying on an outside value passed in as a prop. Each second, the container component calls. to update the. key in its state.

  15. Container/Presentational Pattern

    We can use the Container/Presentational pattern to separate the logic of a component from the view. To achieve this, we need to have a: Presentational Component, that cares about how data is shown to the user. Container Component, that cares about what data is shown to the user. For example, if we wanted to show listings on the landing page, we ...

  16. Presentational And Container Components In React

    And the container components; are components that manage the state of the application. Conclusion. In conclusion, this is a straightforward approach that teaches the Presentational and Container component patterns in React, and their uses. As stated above, You now know how the presentation component helps in rendering information on the page.

  17. Understanding the Container Component Pattern with React Hooks

    The Container Component Pattern. The Container Component pattern (or simply Component pattern) ensures to separate the data fetching logic, managing state from the presentational part. The presentational part has got a dumb name, dumb component. It is because the responsibility of the presentational part is just to render the information passed ...

  18. ReactJS Container and Presentational Pattern in Components

    Benefits of Container/Presentational Pattern. Creates pure functions. Separates render and fetching logic. Makes the components more reusable. Testing the components is easier. Disadvantages of Container/Presentational Pattern. It's alternatives perform better.

  19. Angular Architecture: Container vs Presentational Components Pitfalls

    I have experienced with different architecture types, and I saw 2 ways mainly. 1. container-component pattern strictly, but if it is logical a presentational component can have a container BUT without any property binding. 2. sometimes there are presentational components but most of the @Component-s are containers.

  20. The new approach to the Container Presenter pattern in Angular

    Some of you more than the others, but for some reason, it doesn't work. The container presenter was introduced in 2015. It helps to design the architecture of React application in a more ...

  21. Angular. Container and presentational components (aka smart-dumb)

    The pattern itself is not related to Angular directly, but as Angular is component-driven framework, this pattern is one of the most essential for building modern Angular applications. Container-Presentation pattern. It is believed that good components should be small, focused, independent, testable and most important - reusable.

  22. reactjs

    Presentational/Container components are known as a good separation of concerns pattern in React, and if we search about the topic you'll definitely find Dan Abramov's post regarding that.. But quite some time ago he then updated that post with a statement that can be interpreted that due to the recent adaptability to using Hooks, the presentational/container components pattern is not as ...

  23. National School Lunch Program Meal Pattern

    Endnotes. 1 Food items included in each group and subgroup and amount equivalents. 2 Minimum creditable serving is 1⁄8 cup. One quarter-cup of dried fruit counts as 1⁄2 cup of fruit; 1 cup of leafy greens counts as 1⁄2 cup of vegetables. No more than half of the fruit or vegetable offerings may be in the form of juice.

  24. Making rechargeable batteries more sustainable with fully recyclable

    A team of Penn State chemical engineering researchers has reconfigured the design of solid-state lithium batteries so that all their components can be easily recycled. They published their approach in ACS Energy Letters.

  25. Capstone awards showcase top work

    We recognize outstanding capstone projects in design, innovation and film excellence from ... was further heightened by requiring a system that could safely operate inside a vacuum chamber with minimal metal components. Although the full range was not achieved, the team's design pushed the limits of what a PPT Thrust Balance can accomplish and ...

  26. Cooking up a great prompt: Getting the most from Copilot

    "Write a session abstract of this /[presentation]." Edit text: "Check this product launch rationale for inconsistencies." Create engaging content: "Create a value proposition for [Product X]." Transform documents: "Create an onboarding presentation based on this /[document]." Catch-up on missed items: "What's the latest on ...

  27. 39 Best Infographic PowerPoint Presentation Templates for 2024 (Giant List)

    Find the best infographic slide templates to use for your PowerPoint presentations, and get some useful tips on how to use them. ... Use this infographic template for PowerPoint to design your next portfolio. It contains 34 well-made, unique infographic slide options. It also features: ... When you lay out all four components, you're likely ...

  28. The Controller Pattern: Separate business logic from presentation in

    Summary: The Controller Pattern is an evolution of the Container Pattern. It allows you to clearly separate your logic (like the use of hooks, component-internal state, etc.) from your presentation…

  29. PDF Planning and Design of Complex Solid Waste Facilities To Support Zero

    4. Design for sustainability Target Budget: $10 M • Operations in several buildings • Limited floor space for surges / storage • Inefficient transfer loading • Direct dump self-haul area • Inefficient traffic circulation • Direct dump - fall hazard • Direct dump limited capacity • No space for material storage

  30. Renewable Energy

    Apr 15, 2024 - Are you a professional in the renewable energy field or do you own a company in this sector? Our latest website design, Infinity, is the perfect choice to make your website look attractive, professional, and, of course, modern. The Figma files are perfectly organized, allowing you to easily customize everything you need. *PLEASE NOTE* All images are used for preview purposes ...