How-To Geek

What are presentational and container components in react.

React has a component-based architecture that encourages you to split your codebase into reusable units of functionality.

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.

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

codewithgolu

By: vishwesh

React Presentational vs. Container components: Which to choose?

When building complex React applications, it's important to organize components in a way that maximizes code reusability and maintainability. One common approach is to use presentational and container components.

Presentational components are responsible for rendering UI elements, while container components handle data and application logic. By separating these concerns, we can create a clear separation of concerns and keep our codebase clean and easy to understand.

In this article, we'll explore the differences between presentational and container components, and discuss when and why to use each.

Presentational components

Presentational components, also known as dumb components or stateless components, are responsible for rendering UI elements. They receive data and callbacks from their parent components via props, but they don't manage any state or application logic themselves.

Here's an example of a presentational component that renders a list of items:

In this example, the ItemList component receives an array of items via props and maps over them to render an unordered list of item names. This component doesn't manage any state or application logic itself, making it easy to understand and test.

Presentational components should be as simple and reusable as possible. They should focus on rendering UI elements and avoid complex business logic. By keeping them simple and reusable, we can use them in multiple places throughout our application.

Container components

Container components, also known as smart components or stateful components, are responsible for managing state and application logic. They receive data from their parent components via props, but they also manage their own state and handle any necessary data fetching or updating.

Here's an example of a container component that fetches a list of items and passes them down to a presentational component:

In this example, the ItemListContainer component fetches a list of items from an API using the useEffect hook. It then passes the fetched items down to the ItemList component as a prop. By managing the state and fetching data in the container component, we can keep our presentational components simple and reusable.

Container components should be used sparingly and only when necessary. They can become complex and difficult to understand if we try to put too much application logic into them. Instead, we should aim to keep our container components as simple as possible and delegate as much logic as we can to other components or helper functions.

When to use presentational components

Presentational components should be used whenever we need to render UI elements. They should be as simple and reusable as possible, and should avoid complex business logic. By keeping them separate from our container components, we can make them easier to understand and test.

Here are some examples of when to use presentational components:

  • Rendering lists, tables, or other collections of data
  • Displaying forms, buttons, or other user input elements
  • Showing modals, notifications, or other UI elements

When to use container components

Container components should be used whenever we need to manage state or application logic. They should be as simple as possible, but may be more complex than presentational components as they handle data fetching, data updating, and application logic.

Here are some examples of when to use container components:

  • Fetching data from an API and passing it down to presentational components
  • Handling user input and updating application state accordingly
  • Implementing complex business logic that involves multiple components

It's important to remember that container components should be used sparingly and only when necessary. If we put too much logic into our container components, they can become difficult to understand and maintain.

React presentational and container components provide a clear separation of concerns in our application. Presentational components are responsible for rendering UI elements, while container components handle state and application logic.

By keeping our presentational components simple and reusable, and our container components as simple as possible, we can create a maintainable and scalable codebase.

When deciding whether to use a presentational or container component, consider the component's responsibility and the complexity of the logic it needs to handle. By following this approach, we can create a clean and easy-to-understand React application.

Recent posts

Don't miss the latest trends

Popular Posts

Popular categories.

  • 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
  • ReactJS 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.

Please Login to comment...

author

  • Web Technologies
  • 10 Best Tools to Convert DOC to DOCX
  • How To Summarize PDF Documents Using Google Bard for Free
  • Best free Android apps for Meditation and Mindfulness
  • TikTok Is Paying Creators To Up Its Search Game
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Presentation and Container Components

Follow the react pattern of container/presentation components by refactoring the code and tests..

Paul Everitt

Paul Everitt

jest    react    typescript   

React encourages a separation of concerns. UI components, aka presentation components, aka dumb components, are created by the bushel and managed by container components, aka smart components. The container maintains state, logic, and passes things into the presentation component.

Our Counter component is, as originally intended, a class component with state. Let's make it a presentation component by moving the state up to the container (App), as well as the incrementing logic.

The finished code for this tutorial step is in the repository .

Counter State

We'll start by removing state from the Counter component. Instead, the count is passed in as a prop. Also, the dumb child component will no longer decide the starting value, so remove start from the Counter type definition:

As soon as we do that, the universe starts breaking. TypeScript yells at us in every one of our tests, as our <Counter/> component is not passing in a required prop. Too bad, TypeScript, you'll have to wait.

Next, let's change our Counter component to not have local state. Stateless presentation components are best done with stateless functional components. Let's change <Counter/> to an SFC:

Note that we commented out, for now, the click handler. Finally, delete the import of Component (or use the IDE's Optimize Imports action.)

Let's fix the first two tests in Counter.test.tsx , to see if we are in the ballpark:

These two tests now pass.

Since the <Counter/> component will longer control the starting value, you can remove the should start at zero and should start at another value tests from Counter.test.tsx .

Passing In Click Function

The child component is no longer responsible for the count value. It's passed in from the parent, which keeps track of the count state. So how do we handle clicks?

It sounds weird, but...in the same way. We're going to pass in an arrow function from the parent . Meaning, the parent contains all the logic for what happens when there is a click. All the child needs to know is "when the click event comes in, call the function that was passed to me as a prop."

Here goes. First, since this click handler function will come in as a prop, we need to change CounterProps to model it:

Now that's a type definition, baby. It captures quite a bit of the contract.

Next, use ES6 object destructuring to "unpack" that from the props into the local scope, then refer to that prop in the onClick handler:

Note that the IDE, as you did the unpacking, knew how to autocomplete onCounterIncrease .

Our tests, though, are having compiler trouble again. We broke the component contract, because onCounterIncrease is a mandatory prop. It's easy to fix these first two tests in Counter.test.tsx , because we aren't testing click handling. For example, in the first test:

We are using Jest mock functions to create a disposable arrow function which we passed in as a prop.

Do this for both tests:

Event handling is a bit trickier. We need a "spy" that tells whether our passed-in handler gets called. Also, we don't test whether the value updates, since the container is responsible for that. In fact, we don't need to have a test for "shift-click", as that's part of the handler that will be passed in.

Let's change the third test and delete the last test:

We are simply ensuring that clicking the value calls the callback. We don't even care what it was called with.

Dumb Component Gets a Little Smarter

We deleted the final test because we don't really care how the calling happens. But is that strictly true? What if the presentation component took care of dissecting HTML event information, extracted the relevant data, and then called the callback? That's a better division of responsibilities. The container would then be truly UI-less for this functionality.

First, let's change the contract. Our callback will be called not with the raw event, but with a boolean for the shift information:

Mmmmhh, nice. No more type information details about events.

Our functional component gains a local arrow function which does the extraction and calling:

Our third test can now change, to see if our "spy" was called with a boolean instead of an event object:

The tests in Counter.test.tsx pass.

Updating the Container

We now have a <Counter/> presentation component that passes tests. But we've shifted some important responsibility to the parent. Let's do the updates. Start by opening App.tsx and App.test.tsx side-by-side.

First, this <App/> component will now have some state. We need a type definition for the counter's state. We just so happen to have one left behind in Counter.tsx . Remove the initialState and type definition from that file and paste it into App.tsx :

Our App component needs to maintain state, which for this tutorial means a class-based component for App . Let's use ⌥⏎ (macOS) / Alt+Enter (Windows/Linux) and choose Convert to class component to make that change. We'll then add the generic information in <> and set the state, similar to what we did previously:

The object is a placeholder for the props part of the generic. The App component doesn't have props.

Now it's time for the action. Let's make a "method" (arrow function property) that updates the state. This arrow function will be the handler that's passed into <Counter/> .

Since it is an arrow function, it's this is bound to the component instance, not the event that will be triggered.

With this in place, we can now update the render function:

State is maintained in the parent which it gives to the child, along with an update handler function.

Test the State Updater

And with that, our tests pass again. However, we have dropped any testing to see whether the state actually updated.

Let's add tests in App.test.tsx for the increment operation:

After importing userEvent at the top, we wrote two new tests. Each checks the count before and after clicking. The second simulates a shift-click.

Fantastic, these tests pass. We now have enough confidence to head back over to the browser. Fire up the start run config, reload the browser, click and shift click, then shut down start .

Testing Is Cool

This was a heck of a tutorial step. Let's take a moment and think about how development would have gone the "normal" way. How many times would you have switched to from IDE->browser->IDE? How many clicks would you have to do to each time, checking that your new stuff worked and didn't break your old stuff? When you ran into a problem, would the browser give you a convenient and accurate notice? And when you did have a problem, could you resort to setting browser debugger lines or worse, console.log -based debugging?

It's hard to make yourself get into TDD for React and TypeScript. Once you do, and once you get into the flow, it's a very positive development experience.

React: Presentational vs Container Components

The difference between Presentational and Container Components in React

In React components are often divided into 2 big buckets: presentational components and container components .

Each of those have their unique characteristics.

Presentational components are mostly concerned with generating some markup to be outputted.

They don’t manage any kind of state, except for state related to the presentation

Container components are mostly concerned with the “backend” operations.

They might handle the state of various sub-components. They might wrap several presentational components. They might interface with Redux .

As a way to simplify the distinction, we can say presentational components are concerned with the look , container components are concerned with making things work .

For example, this is a presentational component. It gets data from its props, and just focuses on showing an element:

On the other hand this is a container component. It manages and stores its own data, and uses the presentational component to display it.

Here is how can I help you:

  • COURSES where I teach everything I know
  • THE VALLEY OF CODE your web development manual
  • BOOTCAMP 2024 cohort in progress, next edition in 2025
  • BOOKS 16 coding ebooks you can download for free on JS Python C PHP and lots more
  • SOLO LAB everything I know about running a lifestyle business as a solopreneur
  • Interesting links collection
  • Follow me on X

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

fpaghar profile image

Manipulate Complex API Data Sample In React

Fatemeh Paghar - Mar 25

muhammadazfaraslam profile image

Managing Global State with useReducer and Context API in Next JS 14

Muhammad Azfar Aslam - Apr 3

vatana7 profile image

react-native-collapsable-tab-view onScroll not working

vatana7 - Mar 25

phuocng profile image

Lazy load a background image

Phuoc Nguyen - Apr 3

DEV Community

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

Mastering React Patterns: Presentational and Container Components

Mastering React Patterns: Presentational and Container Components

Samuel Christopher's photo

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 examples of how they can be used effectively.

Target Audience:

This article is suitable for both beginner and experienced React developers who want to enhance their understanding of React patterns and improve the structure of their applications.

Learning Objectives:

By the end of this article, you will gain the following skills:

Recognize the role of Presentational components and Container components.

Create Presentational components and Container components.

Understand how to use Presentational and Container components in a React application.

Comprehend the benefits and use cases of each component type.

Apply best practices for structuring React applications.

Presentational Components:

Presentational components focus on the visual representation of data and are responsible for how things look in a React application. They have the following characteristics:

Concerned with the user interface and rendering data.

Stateless components with no or minimal internal state.

Receive data exclusively through props.

Usually implemented as functional components.

Promote code reusability and maintainability.

Emphasize separation of concerns, readability, and testability.

Prefer composition over inheritance.

Follow declarative programming principles.

Encourage immutability for easier reasoning and preventing rendering errors.

Let's explore an example of a Presentational component:

In the above code, we have a Button component that represents a reusable button with a click event handler, and a Persons component that displays a list of names. These components receive data through props and are focused on rendering the UI.

Container Components:

Container components handle the logic and state management of a React application. They orchestrate the interaction between Presentational components and manage the flow of data. Key characteristics of Container components include:

Focus on the functionality and behavior of the application.

Render Presentational components and pass them data and callbacks.

Maintain the application's state and manage data flow.

Enable code reuse and maintainability.

Emphasize separation of concerns and readability.

Ease reasoning about component dependencies.

Let's examine an example of a Container component:

In this example, the ClickCounter component maintains its own state and renders the Button component as a child. The Form component manages form input, state, and data flow, rendering the Button and Persons components as children. The Container components handle the application logic while utilizing Presentational components for UI rendering.

Real-World Use Cases:

To illustrate the benefits of Presentational and Container components, let's consider a real-world scenario. Suppose you are building a complex application that requires displaying a list of products. The ProductList component, responsible for rendering the list, can be a Presentational component that receives the product data as props. The ProductPage component, responsible for fetching the product data and handling user interactions, can be a Container component that manages the state and data flow, rendering the ProductList component.

By separating concerns and encapsulating logic, Presentational and Container components promote reusability, maintainability, and code readability.

Best Practices and Tips:

To effectively implement Presentational and Container components in your React applications, consider the following best practices:

Maintain a clear separation between Presentational and Container components.

Keep Presentational components as simple as possible, focusing on rendering UI based on props.

Offload business logic and state management to Container components.

Utilize the props and callback functions to pass data and handle user interactions between components.

Follow naming conventions and folder structure that align with the component types.

Write comprehensive tests for both Presentational and Container components.

Conclusion:

In this article, we explored the concepts of Presentational and Container components, their characteristics, benefits, and use cases. By implementing these patterns in your React applications, you can achieve better code organization, maintainability, and reusability. Understanding the separation of concerns between Presentational and Container components empowers you to build scalable and well-structured React applications. Happy coding!

Container vs. Presentation Components

One of the fundamental concepts of component architecture in Angular applications is to find the right balance between container and presentation components.

Let’s define what those are:

  • Presentation components are reusable, simple pieces of UI. Think buttons, dialogs, cards, nav bars, etc.
  • Container components are the exact opposite: They’re not reusable. They’re tied to a specific use case. Those are usually entire screens or sub-screens, the app component, etc.

From a code standpoint, container components use services to interact with the back end. Such components know where to get the data using those services and then feed that data to their children using inputs, which are presentation components:

presentation component vs container component

A simple way to identify those components is that presentation components only have inputs and outputs , no dependency injection. Container components have dependencies injected and most likely no inputs or outputs.

When to use container vs. presentation components?

Suppose you have components that are good candidates to become presentation components but are using services. In that case, you can most likely inject that service in its parent container and then pass the data to said component using an input. That way, your presentation component will be reusable in other places without being tied to a specific use case.

Of course, just like with any best practice, there are exceptions to consider. There are times when reusability makes sense and others when it does not. Do not force your components into one of these categories if it doesn’t make sense, but give it a try if it’s a quick win. Your application architecture (and possibly performance – stay tuned for more on that soon) will thank you later.

' src=

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.

  • Table of Contents
  • Testimonials
  • React from Zero Book
  • 30 Days of React
  • React Native Book
  • Fullstack React Book
  • Get The Book

presentation component vs container component

Using Presentational and Container Components with Redux

In the last chapter, we added complexity to both the state as well as the view-layer of our application. To support threads in our app, we nested message objects inside of thread objects in our state tree. By using reducer composition, we were able to break up the management of our more complex state tree into smaller parts.

We added a new React component to support our threaded model, ThreadTabs , which lets the user switch between threads on the view. We also added some complexity to existing components.

At the moment, we have four React components in our app. Every React component interacts directly with the Redux store. App subscribes to the store and uses getState() to read the state and passes down this state as props to its children. Child components dispatch actions directly to the store.

In this chapter, we'll explore a new paradigm for organizing our React components. We can divide up our React components into two types: presentational components and container components . We'll see how doing so limits knowledge of our Redux store to container components and provides us with flexible and re-usable presentational components.

Presentational and container components

In React, a presentational component is a component that just renders HTML . The component's only function is presentational markup. In a Redux-powered app, a presentational component does not interact with the Redux store.

The presentational component accepts props from a container component . The container component specifies the data a presentational component should render. The container component also specifies behavior. If the presentational component has any interactivity — like a button — it calls a prop-function given to it by the container component. The container component is the one to dispatch an action to the Redux store:

presentation component vs container component

Take a look at the ThreadTabs component:

class ThreadTabs extends React . Component { handleClick = ( id ) => { store . dispatch ( { type : 'OPEN_THREAD' , id : id , } ) ; } ; render ( ) { const tabs = this . props . tabs . map ( ( tab , index ) => ( < div key = { index } className = { tab . active ? 'active item' : 'item' } onClick = { ( ) => this . handleClick ( tab . id ) } > { tab . title } </ div > ) ) ; return ( < div className = ' ui top attached tabular menu ' > { tabs } </ div > ) ; } }

At the moment, this component both renders HTML (the text field input) and communicates with the store. It dispatches the OPEN_THREAD action whenever a tab is clicked.

But what if we wanted to have another set of tabs in our app? This other set of tabs would probably have to dispatch another type of action. So we'd have to write an entirely different component even though the HTML it renders would be the same.

What if we instead made a generic tabs component, say Tabs ? This presentational component would not specify what happens when the user clicks a tab. Instead, we could wrap it in a container component wherever we want this particular markup in our app. That container component could then specify what action to take by dispatching to the store.

We'll call our container component ThreadTabs . It will do all of the communicating with the store and let Tabs handle the markup. In the future, if we wanted to use tabs elsewhere — say, in a "contacts" view that has a tab for each group of contacts — we could re-use our presentational component:

presentation component vs container component

Splitting up ThreadTabs

We'll split up ThreadTabs by first writing the presentational component Tabs . This component will only be concerned with rendering the HTML — the array of horizontal tabs. It will also expect a prop, onClick . The presentational component will allow its container component to specify whatever behavior it wants when a tab is clicked.

Let's add Tabs to App.js now. Write it above the current ThreadTab component. The JSX for the HTML markup is the same as before:

const Tabs = ( props ) => ( < div className = ' ui top attached tabular menu ' > { props . tabs . map ( ( tab , index ) => ( < div key = { index } className = { tab . active ? 'active item' : 'item' } onClick = { ( ) => props . onClick ( tab . id ) } > { tab . title } </ div > ) ) } </ div > ) ;

A unique aspect of our new presentational component is how it's declared. So far, we've been using ES6 classes like this:

React components declared in this manner are wrapped in React's component API. This declaration gives the component all of the React-specific features that we've been using, like lifecycle hooks and state management.

However, as we cover in the "Advanced Components" chapter, React also allows you to declare stateless functional components . Stateless functional components, like Tabs , are just JavaScript functions that return markup. They are not special React objects.

Because Tabs does not need any of React's component methods, it can be a stateless component.

In fact, all our presentational components can be stateless components. This reinforces their single responsibility of rendering markup. The syntax is terser. What's more, the React core team recommends using stateless components whenever possible. Because these components are not "dressed up" with any of the capabilities of React component objects, the React team anticipates there will be many performance advantages introduced for stateless components in the near future.

As we can see, the first argument passed in to a stateless component is props :

const Tabs = ( props ) => (

Because Tabs is not a React component object, it does not have the special property this.props . Instead, parents pass props to stateless components as an argument. So we'll access this component's props everywhere using props as opposed to this.props .

Our map call for Tabs is in-line, nested inside of the div tag in the function's return value. You could also put this logic above the function's return statement, like we had before in the render function of ThreadTabs . It's a matter of stylistic preference.

Our presentational component is ready. Let's see what the container component that uses it looks like. Modify the current ThreadTabs component:

class ThreadTabs extends React . Component { render ( ) { return ( < Tabs tabs = { this . props . tabs } onClick = { ( id ) => ( store . dispatch ( { type : 'OPEN_THREAD' , id : id , } ) ) } /> ) ; } }

Although we don't use any of React's component methods, we're still using an ES6 class component as opposed to declaring a stateless component. We'll see why in a moment.

Our container component specifies the props and behavior for our presentational component. We set the prop tabs to this.props.tabs , specified by App . Next, we set the prop onClick to a function that calls store.dispatch() . We expect Tabs to pass the id of the clicked tab to this function.

If we were to test the app out now, we'd be happy to note that our new container/presentational component combination is working.

However, there's one odd thing about ThreadTabs : It sends actions to the store directly with dispatch, yet at the moment it's reading from the store indirectly through props (through this.props.tabs ). App is the one reading from the store and this data trickles down to ThreadTabs . But if ThreadTabs is dispatching directly to the store, is this indirection for reading from the store necessary?

Instead, we can have all of our container components be responsible for both sending actions to the store and reading from it.

In order to achieve this with ThreadTabs , we can subscribe directly to the store in componentDidMount , the same way that App does:

class ThreadTabs extends React . Component { componentDidMount ( ) { store . subscribe ( ( ) => this . forceUpdate ( ) ) ; }

Then, inside of render , we can read state.threads directly from the store with getState() . We'll generate tabs here using the same logic that we used in App :

render ( ) { const state = store . getState ( ) ; const tabs = state . threads . map ( t => ( { title : t . title , active : t . id === state . activeThreadId , id : t . id , } ) ) ;

Now we don't need to read from this.props at all. We pass Tabs the tabs variable that we created:

return ( < Tabs tabs = { tabs } onClick = { ( id ) => ( store . dispatch ( { type : 'OPEN_THREAD' , id : id , } ) ) } /> ) ;

Our Tabs component is purely presentational. It specifies no behavior of its own and could be dropped-in anywhere in the app.

The ThreadTabs component is a container component. It renders no markup. Instead, it interfaces with the store and specifies which presentational component to render. The container component is the connector of the store to the presentational component.

Our presentational and container component combination, in full:

const Tabs = ( props ) => ( < div className = ' ui top attached tabular menu ' > { props . tabs . map ( ( tab , index ) => ( < div key = { index } className = { tab . active ? 'active item' : 'item' } onClick = { ( ) => props . onClick ( tab . id ) } > { tab . title } </ div > ) ) } </ div > ) ; class ThreadTabs extends React . Component { componentDidMount ( ) { store . subscribe ( ( ) => this . forceUpdate ( ) ) ; } render ( ) { const state = store . getState ( ) ; const tabs = state . threads . map ( t => ( { title : t . title , active : t . id === state . activeThreadId , id : t . id , } ) ) ; return ( < Tabs tabs = { tabs } onClick = { ( id ) => ( store . dispatch ( { type : 'OPEN_THREAD' , id : id , } ) ) } /> ) ; } }

In addition to the ability to re-use our presentational component elsewhere in the app, this paradigm gives us another significant benefit: We've de-coupled our presentational view code entirely from our state and its actions. As we'll see, this approach isolates all knowledge of Redux and our store to our app's container components. This minimizes the switching costs in the future. If we wanted to move our app to another state management paradigm, we wouldn't need to touch any of our app's presentational components.

Splitting up Thread

Let's continue refactoring with our new design pattern.

Thread receives the thread as a prop and contains all the markup for rendering the messages inside of that thread as well as MessageInput . The component will dispatch to the store a DELETE_MESSAGE action if a message is clicked.

Part of rendering the view for a thread involves rendering the view for its messages. We could have separate container and presentational components for threads and messages. In this setup, the presentational component for a thread would render the container component for a message.

But because we don't anticipate ever rendering a list of messages outside of a thread, it's reasonable to just have the container component for the thread also manage the presentational component for a message.

We can have one container component, ThreadDisplay . This container component will render the presentational component Thread :

presentation component vs container component

For the list of messages, we can have Thread render another presentational component, MessageList .

But what about the component MessageInput ? Like our previous version of ThreadTabs , the component contains two responsibilities. The component renders markup, a single text field with a submit button. In addition, it specifies the behavior for what should happen when the form is submitted.

We could, instead, just have a generic presentational component. TextFieldSubmit only renders markup and allows its parent to specify what happens when the text field is submitted. ThreadDisplay , through Thread , could control the behavior of this text field.

With this design, we'd have one container component for a thread up top. The presentational component Thread would be a composite of two child presentational components, MessageList and TextFieldSubmit :

presentation component vs container component

Let's first rename our current Thread component to ThreadDisplay to avoid confusion:

We'll begin at the bottom, writing the presentational components TextFieldSubmit and MessageList . We'll work our way up to Thread and then ThreadDisplay .

TextFieldSubmit

Like with ThreadTabs , MessageInput has two distinct roles: the component both renders the HTML for an input field but also specifies what the behavior around submitting that input field should be (dispatching ADD_MESSAGE ).

If we remove the dispatch call from MessageInput , we'd be left with a generic component that just rendered markup: a text field with an adjacent submit button. The presentational component will allow its container component to specify whatever behavior it wants when the input field is submitted.

Let's rename MessageInput to TextFieldSubmit to make it more generic. The only additional change we need to make is in handleSubmit() . We'll have TextFieldSubmit expect a single prop, onSubmit . Instead of dispatching to the store directly, it will invoke this prop-function:

class TextFieldSubmit extends React . Component { state = { value : '' , } ; onChange = ( e ) => { this . setState ( { value : e . target . value , } ) } ; handleSubmit = ( ) => { this . props . onSubmit ( this . state . value ) ; this . setState ( { value : '' , } ) ; } ;

MessageList

The MessageList component will accept two props: messages and onClick . As before, this presentational component will not specify any behavior. As a stateless component, it will only render HTML.

Write it below TextFieldSubmit and above the ThreadDisplay component in App.js :

const MessageList = ( props ) => ( < div className = ' ui comments ' > { props . messages . map ( ( m , index ) => ( < div className = ' comment ' key = { index } onClick = { ( ) => props . onClick ( m . id ) } > < div className = ' text ' > { m . text } < span className = ' metadata ' > @ { m . timestamp } </ span > </ div > </ div > ) ) } </ div > ) ;

The map that we perform over props.messages is the same logic we had previously in Thread . We perform it in-line, nested inside of the div tag which is responsible for styling. The three changes:

  • We perform the map over props.messages as opposed to this.props.threads
  • The onClick attribute is now set to props.onClick
  • For brevity, we're using the variable m in place of message
You could optionally break this presentational component down further by adding another component, Message . The markup for each message is still simple enough that we opted not to do this just yet here.

We have two presentational components related to displaying a thread. One is MessageList , which renders all of the messages in that thread. The other is TextFieldSubmit , a generic text field entry that we're going to have submit new messages to the thread.

We're collecting these two presentational components under Thread , another presentational component. The container component ThreadDisplay will render Thread which in turn will render MessageList and TextFieldSubmit .

We anticipate that ThreadDisplay will pass Thread three props:

  • thread : The thread itself
  • onMessageClick : The message click handler
  • onMessageSubmit : The text field submit handler

We'll have Thread pass along the appropriate props to each of its child presentational components:

const Thread = ( props ) => ( < div className = ' ui center aligned basic segment ' > < MessageList messages = { props . thread . messages } onClick = { props . onMessageClick } /> < TextFieldSubmit onSubmit = { props . onMessageSubmit } /> </ div > ) ;

This page is a preview of Fullstack React: The Complete Book on ReactJS and Friends.

Get the rest of this chapter plus hundreds of pages of React instruction, 5 sample projects , a screencast, and more.

presentation component vs container component

Get A Full Sample Chapter PDF

Want to build your first React app? Put in your email below and we'll email you a PDF that walks you through building an app in React - step-by-step, from empty folder to a working app.

presentation component vs container component

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

presentation component vs container component

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 vs container component

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 ?
  • Introduction
  • 1. React Native Internals 📡
  • 2. Setting up the project 🌈
  • 3. See it in action! 🎬
  • 4.1. Customizing the project structure
  • 4.2. Creating basic components and writing platform-specific code
  • 5.1. ESLint: The guardian of code conventions ⚔️
  • 5.2. Github Pre-push/Pre-commit Hooks
  • 5.3. Environment Variables
  • 5.4. Speed up development with some and ES7 features 🤘
  • 6.1. Jest setup
  • 6.2. Snapshots
  • 6.3. Testing stateful components using Enzyme
  • 6.4. Mocking RN modules
  • 7.1. Theme Variables
  • 7.2. Common Styles/Mixins
  • 7.3. Separating styles from component
  • 8.1. Redux setup
  • 8.2. Presentational VS Containers
  • 9.1. Using React-navigation
  • 9.2. Integrating with redux store
  • 9.3. File Structure for routes
  • 10.1. Android Build setup
  • 10.2. iOS Build setup
  • 11.1. Custom Icon set
  • 12.1. Adding language toggle feature
  • 12.2. Integration with react-navigation
  • 13.1. Android Native Modules
  • 13.2. iOS Native Modules
  • 14. References
  • 15. The End
  • Published with GitBook

React Made Native Easy

Presentational components vs container components.

When writing code in React or React Native, we often wonder how to structure our code so that it makes our life much easier when handling state changes, data flow and renders, etc. There is a pattern which helps in organizing React based applications - splitting the components into presentational and containers.

Presentational components

Presentational components are those components whose only job is to render a view according to the styling and data passed to them. Essentially, they do not contain any business logic. That's why they are sometimes also called dumb components . This means that they don't have direct access to Redux or other data stores. Data is passed to them via props.

According to Dan Abramov in his blog https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0 , presentational components:

  • are concerned with how things look.
  • have markup and styles of their own.
  • have no dependencies on the rest of the app, such as Redux stores.
  • don’t specify how the data is loaded or mutated.
  • receive data and callbacks exclusively via props.
  • rarely have their own state (when they do, it’s UI state rather than data).

An example of a Dumb/Presentational component would be:

Container components

Container components are those React components which have access to the store. These components make API calls, do processing and contain the business logic of the app. Container components shouldn't have the view logic or presentational logic. The job of container components is to compute the values and pass them as props to the presentational components. Hence, these components are sometimes also referred to as Smart Components.

Therefore, container components:

  • are concerned with how things work.
  • don’t usually have any markup of their own except for some wrapping Views, and never have any styles.
  • provide the data and behavior to presentational or other container components.
  • call Redux actions and provide these as callbacks to the presentational components.
  • are often stateful, as they tend to serve as data sources.
  • are usually generated using higher order components such as connect() from React Redux, createContainer() from Relay, or Container.create() from Flux Utils, rather than written by hand.

An example of a Smart/Container component would be:

In the above example, if you notice, our Container component does not do any kind of layouting or styling. It only manages the business logic. This helps us separate the concerns "Styling/Layouting" and "Business Logic".

The Container-Presentational pattern gives us many benefits:

  • Less code duplication. Because you are forced to move all the layout components out as separate presentational components, you can now directly reuse them instead of copy-pasting the code in every page.
  • Presentational components are essentially your app’s View layer. Hence, you can change the styling without touching the app's logic.
  • Better separation of concerns. You understand your app and your UI better by writing components this way.
  • Better reusability. You can use the same presentational component with completely different state sources, and turn those into separate container components that can be further reused.

Back to Code

Let's organize our project to include presentational and container components pattern.

First, let's add a new reducer to manage our content (title and text).

Modify the action file to include these:

app/redux/actions/index.actions.js

Notice the use of createAction . As the comment says, we are essentially replacing:

To do this we need to include another package.

yarn add redux-actions

Now, let's create the corresponding reducer.

app/redux/reducers/content.reducer.js

Now, let's add the reducer to the root reducer.

app/redux/reducers/root.reducer.js

Finally, it's time to create our first Smart component.

Create a new file under /pages with the name Home.page.js

app/pages/Home.page.js

If you notice the job of Home Page is just to fetch data and provide logical functions to the view layer.

The corresponding view layer would look like this:

app/components/Home/Home.component.js

Finally, let's modify our app container to include the page instead of the component.

app/App.container.js

Our app should now look like this:

presentation component vs container component

Although the app looks exactly the same, it is working in a slightly different manner.

If you paid attention you would notice:

  • We now have a clear demarcation between the view and logic layer. Hence, we will know exactly where to look in case there is either a UI or logical bug.
  • We are not importing react-native at all in any part of the whole code base except in app/components/ . This means porting the project to any other platform like Electron is as simple as rewriting the app/components directory. The logical layer remains intact.
  • The code is easier to maintain as the flow of data to the view layer happens via props.

presentation component vs container component

The code till here can be found on the branch chapter/9/9.2

containerd vs. Docker: Understanding Their Relationship and How They Work Together

presentation component vs container component

Savannah Ostrowski

During the past decade, containers have revolutionized software development by introducing higher levels of consistency and scalability. Now, developers can work without the challenges of dependency management, environment consistency, and collaborative workflows.

When developers explore containerization, they might learn about container internals, architecture, and how everything fits together. And, eventually, they may find themselves wondering about the differences between containerd and Docker and how they relate to one another.

In this blog post, we’ll explain what containerd is, how Docker and containerd work together, and how their combined strengths can improve developer experience.

Containerd 2400x1260 1

What’s a container?

Before diving into what containerd is, I should briefly review what containers are. Simply put, containers are processes with added isolation and resource management. Containers have their own virtualized operating system with access to host system resources. 

Containers also use operating system kernel features. They use namespaces to provide isolation and cgroups to limit and monitor resources like CPU, memory, and network bandwidth. As you can imagine, container internals are complex, and not everyone has the time or energy to become an expert in the low-level bits. This is where container runtimes, like containerd, can help.

What’s containerd?

In short, containerd is a runtime built to run containers. This open source tool builds on top of operating system kernel features and improves container management with an abstraction layer, which manages namespaces, cgroups, union file systems, networking capabilities, and more. This way, developers don’t have to handle the complexities directly. 

In March 2017 , Docker pulled its core container runtime into a standalone project called containerd and donated it to the Cloud Native Computing Foundation (CNCF).  By February 2019 , containerd had reached the Graduated maturity level within the CNCF, representing its significant development, adoption, and community support. Today, developers recognize containerd as an industry-standard container runtime known for its scalability, performance, and stability.

Containerd is a high-level container runtime with many use cases. It’s perfect for handling container workloads across small-scale deployments, but it’s also well-suited for large, enterprise-level environments (including Kubernetes). 

A key component of containerd’s robustness is its default use of Open Container Initiative (OCI)-compliant runtimes. By using runtimes such as runc (a lower-level container runtime), containerd ensures standardization and interoperability in containerized environments. It also efficiently deals with core operations in the container life cycle, including creating, starting, and stopping containers.

How is containerd related to Docker?

But how is containerd related to Docker? To answer this, let’s take a high-level look at Docker’s architecture (Figure 1). 

Containerd facilitates operations on containers by directly interfacing with your operating system. The Docker Engine sits on top of containerd and provides additional functionality and developer experience enhancements.

Containerd diagram v1

How Docker interacts with containerd

To better understand this interaction, let’s talk about what happens when you run the docker run command:

  • After you select enter, the Docker CLI will send the run command and any command-line arguments to the Docker daemon ( dockerd ) via REST API call.
  • dockerd will parse and validate the request, and then it will check that things like container images are available locally. If they’re not, it will pull the image from the specified registry.
  • Once the image is ready, dockerd will shift control to containerd to create the container from the image.
  • Next, containerd will set up the container environment. This process includes tasks such as setting up the container file system, networking interfaces, and other isolation features.
  • containerd will then delegate running the container to runc using a shim process. This will create and start the container.
  • Finally, once the container is running, containerd will monitor the container status and manage the lifecycle accordingly.

Docker and containerd: Better together 

Docker has played a key role in the creation and adoption of containerd, from its inception to its donation to the CNCF and beyond. This involvement helped standardize container runtimes and bolster the open source community’s involvement in containerd’s development. Docker continues to support the evolution of the open source container ecosystem by continuously maintaining and evolving containerd.

Containerd specializes in the core functionality of running containers. It’s a great choice for developers needing access to lower-level container internals and other advanced features. Docker builds on containerd to create a cohesive developer experience and comprehensive toolchain for building, running, testing, verifying, and sharing containers.

Build + Run

In development environments, tools like Docker Desktop , Docker CLI , and Docker Compose allow developers to easily define, build, and run single or multi-container environments and seamlessly integrate with your favorite editors or IDEs or even in your CI/CD pipeline. 

One of the largest developer experience pain points involves testing and environment consistency. With Testcontainers , developers don’t have to worry about reproducibility across environments (for example, dev, staging, testing, and production). Testcontainers also allows developers to use containers for isolated dependency management, parallel testing, and simplified CI/CD integration.

By analyzing your container images and creating a software bill of materials (SBOM), Docker Scout works with Docker Desktop, Docker Hub , or Docker CLI to help organizations shift left. It also empowers developers to find and fix software vulnerabilities in container images, ensuring a secure software supply chain.

Docker Registry serves as a store for developers to push container images to a shared repository securely. This functionality streamlines image sharing, making maintaining consistency and efficiency in development and deployment workflows easier. 

With Docker building on top of containerd, the software development lifecycle benefits from the inner loop and testing to secure deployment to production.

Wrapping up

In this article, we discussed the relationship between Docker and containerd. We showed how containers, as isolated processes, leverage operating system features to provide efficient and scalable development and deployment solutions. We also described what containerd is and explained how Docker leverages containerd in its stack. 

Docker builds upon containerd to enhance the developer experience, offering a comprehensive suite of tools for the entire development lifecycle across building, running, verifying, sharing, and testing containers. 

Start your next projects with containerd and other container components by checking out Docker’s open source projects and most popular open source tools . 

  • Subscribe to the Docker Newsletter .
  • Get the latest release of Docker Desktop .
  • Vote on what’s next! Check out our public roadmap .
  • Have questions? The Docker community is here to help .
  • New to Docker? Get started .

0 thoughts on "containerd vs. Docker: Understanding Their Relationship and How They Work Together"

Debian’s Dedication to Security: A Robust Foundation for Docker Developers

From misconceptions to mastery: enhancing security and transparency with docker official images, kubecon eu 2024: highlights from paris.

Mar 27, 2024

  • Engineering

Platform products

  • Red Hat Enterprise Linux A flexible, stable operating system to support hybrid cloud innovation.
  • Red Hat OpenShift A container platform to build, modernize, and deploy applications at scale.
  • Red Hat Ansible Automation Platform A foundation for implementing enterprise-wide automation.
  • Start a trial Assess a product with a no-cost trial.
  • Buy online Buy select products and services in the Red Hat Store.

Cloud providers: Amazon Web Services, Microsoft Azure, and Google Cloud

Featured cloud services

  • Red Hat OpenShift Service on AWS
  • Red Hat OpenShift AI
  • Microsoft Azure Red Hat OpenShift

By category

  • Application platform
  • Artificial intelligence
  • Edge computing
  • IT automation
  • Linux standardization

By organization type

  • Financial services
  • Industrial sector
  • Media and entertainment
  • Public sector
  • Telecommunications

By customer

  • British Army
  • HCA Healthcare
  • Macquarie Bank
  • Tata Consultancy Services
  • Search all success stories
  • Open Innovation Labs
  • Technical Account Management

Training & certification

  • All courses and exams
  • All certifications
  • Verify a certification
  • Skills assessment
  • Learning subscription
  • Learning community
  • Red Hat Academy
  • Connect with learning experts
  • Red Hat System Administration I (RH124)
  • Red Hat OpenShift Administration II (DO280)
  • Red Hat Certified Engineer (RHCE)
  • Application modernization
  • Cloud computing
  • Cloud-native applications
  • Virtualization
  • See all topics
  • What are cloud services?
  • What is edge computing?
  • What is hybrid cloud?
  • Why build a Red Hat cloud?
  • Cloud vs. edge
  • Red Hat OpenShift vs. Kubernetes
  • Learning Ansible basics
  • What is Linux?

More to explore

  • Customer success stories
  • Events and webinars
  • Podcasts and video series
  • Resource library
  • Training and certification

For customers

  • Our partners
  • Red Hat Ecosystem Catalog
  • Find a partner

For partners

  • Partner Connect
  • Become a partner
  • Access the partner portal
  • Our company
  • How we work
  • Our social impact
  • Development model
  • Subscription model
  • Product support

Open source

  • Open source commitments
  • How we contribute
  • Red Hat on GitHub

Company details

  • Analyst relations

Communities

  • For system administrators
  • For architects
  • Customer advocacy

Recommendations

As you browse redhat.com, we'll recommend resources you may like. For now, try these.

  • All Red Hat products
  • Tech topics
  • Red Hat resources

Select a language

  • Training & services

Red Hat blog

Introducing Confidential Containers Trustee: Attestation Services Solution Overview and Use Cases

  • Back to all posts

Tags: Products , Topics

In confidential computing environments,  attestation is crucial in verifying the trustworthiness of the location where you plan to run your workload or where you plan to send confidential information. Before actually running the workload or transmitting the confidential information, you need to perform  attestation .

This blog provides an overview of the components implemented in the  confidential containers (CoCo) to support the  IETF RATS model   (Remote ATtestation procedureS Architecture) . The components include the Attestation Service (AS), Key Broker Service (KBS), Reference Value Provider Service (RVPS), Attestation Agent (AA), and Confidential Data Hub (CDH). The AS, KBS, and RVPS components are part of the  Trustee project , whereas the AA and CDH are part of the  guest-components project in CoCo.

We begin by introducing the RATS model and its components. After that, we discuss the Trustee project, its various components, and how they relate to the RATS model. Finally, we present a few use cases that demonstrate the usage of the CoCo Trustee and guest-components project.

RATS architecture and key components

The key components in the RATS architecture are described in the following diagram:

RATS architecture and key components

  • Attester - provides  Evidence , which is evaluated and appraised to decide its trustworthiness (for instance, a test to see whether it’s authorized to perform some action). Evidence may include configuration data, measurements, telemetry, or inferences.
  • Verifier - evaluates the validity of the evidence received from the attester and produces  attestation results , which are sent to the Relying party. Attestation results typically include information regarding the Attester, while the Verifier vouches for the validity of the results.
  • Relying party - depends on the validity of information originating from the attester for reliably applying an action. This information can come from the verifier or directly through the attester.
  • Relying party owner - authorized to configure the appraisal policy that the  relying party will use when receiving the attestation results (such as admin).
  • Verifier owner - authorized to configure the appraisal policy the verifier will use when receiving the evidence.
  • Endorser - for us, the hardware manufacturer who provides an  endorsement , which the  verifier uses to validate the evidence received from the attester. The endorsement is a secure statement the Endorser vouches for on the integrity of an Attester's various capabilities
  • Reference Value Provider - for us the hardware manufacturer who provides  reference values , which the verifier uses to verify that claims were recorded by the attester. Reference values are, for example, golden measurements or nominal values.

In practice, the data flow between the verifier, attester, and relying party can be done through the  passport check model and  background check model .

Passport check model

In the passport model, the  attester validates an identification token with the  verifier . It then presents the identification token to the  relying party . It's a similar process to when you present your passport at an airport to confirm your own identity when entering a country.

In this model, the attester requests the passport from the verifier by providing  evidence and receives a passport in the form of  attestation results . It can now interact directly with the relying party by presenting its passport (attestation result).

The following diagram shows this flow: 

attestation-services-solution

Background check model

In the background check model, the  relying party asks for verification each time the  attester presents its evidence. This is similar to performing a full background check on an individual every time the individual enters a country.

The attester provides  evidence to the relying party, which forwards it directly to the verifier. The verifier compares the evidence with the  appraised policy it contains, and returns an  attestation result to the relying party. The relying party compares the attestation results with its own  appraisal policy .

Unlike a passport model, where the attester sends  attestation results to the relying party, the background model requires the attester to send the relying party  evidence (which is sent as-is to the verifier).

The following diagram illustrates the background check model:

attestation-services-solution-image3

The Trustee project

The trustee project (previously known as  CoCo KBS ) includes components deployed on a trusted side and used to verify whether the remote workload is running in a trusted execution environment (TEE). It also verifies that the remote environment uses the expected software and hardware versions.

This diagram shows the architecture for the Trustee model:

attestation-services-solution

The  left side includes the  guest components running inside the TEE, including the Attestation Agent (AA) and Confidential Data Hub (CDH). The  right side includes the external components, which the guest components interact with, such as the Key Broker Service (KBS), Attestation Service (AS), and the Reference Value Provider Service (RVPS).

Trustee and guest components

Key broker service (kbs).

The Key Broker Service (KBS) facilitates remote attestation and managing and delivering secrets. Equating this to the RATS model, the KBS is the  relying party entity. The KBS, however, doesn’t validate the attestation evidence. Instead, it uses the attestation service (AS) to verify the TEE evidence.

Attestation Service (AS)

The Attestation Service (AS) is responsible for validating the TEE evidence. This includes evidence from the following TEEs: Intel TDX, Intel SGX, AMD SEV-SNP, ARM CCA, Hygon CSV, and more.

When mapped to the RATS model, the AS is the equivalent of the  verifier .

The AS receives attestation evidence and returns an attestation token containing the results of a two-step verification process. Note that the KBS is the client of the AS, however the evidence originates from the attestation agent (AA).

The following diagram shows the AS components:

attestation-services-solution-image5

The AS runs the following verification process:

  • Verify the formatting and the origin of the evidence - for example, checking the signature of the evidence. This is accomplished by one of the platform-specific  Verifier Drivers .
  • Evaluate the claims provided in the evidence - for example, validating that the measurements are what the client expects. This is done by a  Policy Engine with help from the  RVPS .

Verifier driver

A verifier driver parses the attestation evidence provided by the hardware TEE. It performs the following tasks:

  • Verifies the hardware TEE signature of the TEE quote and report provided in the evidence
  • Receives the evidence and organizes the status into a JSON format to be returned

Policy Engine

The AS allows users to upload their own policies when performing evidence verification. When an attestation request is received by the AS, it uses a policy ID in the request to decide which policies should be evaluated. The results of all policies evaluated are included in the attestation response.

Reference Value Provider Service (RVPS)

The reference value provider service (RVPS) is a component in the AS responsible for verifying, storing, and providing reference values. RVPS receives and verifies inputs from the software supply chain, stores the measurement values, and generates reference value claims for the AS. This operation is performed based on the evidence verified by the AS.

The following diagram shows the RVPS components:

attestation-services-solution

RVPS contains the preprocessors, extractors, and store components:

Preprocessors

These are plugins that preprocess the reference value registration messages before sending it to extractors.

These are plugins that process different types of provenance in the input message. Each plugin consumes the input message, and then generates an output  Reference value.

The store component provides persistent storage for the reference values.

Attestation Agent (AA)

The Attestation Agent (AA) is the entity running inside the TEE that connects to the KBS in order to perform attestation.  AA is responsible for sending the evidence (claims) from the TEE to prove the trustworthiness of the environment.

Confidential Data Hub (CDH)

The Confidential Data Hub (CDH) facilitates secure key retrieval for kata-agent and applications. It also provides additional services, such as secure mount for external storage or key management client services to retrieve keys directly from external Key Management Services. The secure mount service enables mounting of encrypted storage inside the TEE. We'll cover the secure mount service in a subsequent blog.

The following diagram shows the CDH components:

attestation-services-solution

Resources for learning about the attestation flow

For an  overview of attestation , read our  Learn about Confidential Computing Attestation blog series.

For details on  attestation flow in confidential containers , read our  Understanding the Confidential Containers Attestation Flow article.

For a  step-by-step flow of confidential containers attestation on Azure cloud, read our  Confidential Containers on Azure with OpenShift: A technical deep dive article.

Mapping Trustee components to the RATS model

This is how the RATS model maps to the Trustee components model:

attestation-services-solution-image8

Note the following:

  • The  Attester functionally is performed by the  AA and  CDH guest side components.
  • The  Verifier is mapped to the  AS .
  • The  Relying party is mapped to the  KBS receiving attestation results from the AS, and performing actions based on the results.
  • The  Endorser usually originates from the platform manufacturer (Intel, AMD, IBM, and so on), so it can be the manufacturer itself or a CSP that got endorsed by the hardware manufacturer.
  • The  Reference Value Provider is mapped to the  RVPS and provides the endorsed reference. Note that reference values do not originate from the hardware manufacturer, but rather they reference measurements of the kernel, firmware image, and so on. They are trusted artifacts meaning signed by an identity you can trust and are used for performing the verification.
  • The  Verify owner and  Relying Party owner are the entities who operate the KBS and AS on the user's behalf.

The background check model is a common way to configure the KBS and AS components, so we present it before the passport model. The following diagram shows the model: 

attestation-services-solution-image9

In this model, the AA communicates with the KBS providing the hardware evidence and the KBS communicates with the AS to verify it. After the evidence is verified, the KBS releases the secrets back to the CDH when requested.

In background check mode, the KBS is the relying party, the AS is the verifier, and the AA is the attester.

Passport model

In the passport model, the validation of evidence and provisioning of resources are typically handled by  different KBSes. The following diagram shows the model: 

attestation-services-solution-image10

We now have 2 KBS entities:

  • The first KBS, with the AS, verifies the evidence from the guest.
  • The second KBS provides secrets to the guest.

The AA interacts with  upper KBS + AS (Trustee 1) in order to attest, verify the evidence, and receive a token (a passport). It then requests the secret resources from the lower KBS (Trustee 2) .

In practice, we recommend using the passport model when the attestation and resource provisioning are handled by separate entities.

Attestation use cases leveraging Trustee components

There are many use cases that can leverage the Trustee and guest components. For simplicity, we focus on the  background check model (a single KBS) and not the  passport model (with two KBS entities).

Attestation for virtual machines (VMs) and their workloads

Confidential VMs (CVMs) leverage hardware-based security features, such as AMD SEV-SNP (Secure Encrypted Virtualization-Secure Nested Paging) or Intel TDX (Trust Domain Extensions) to provide a secure execution environment for sensitive workloads. These VMs confirm that code and data remain encrypted and isolated, even from other privileged softwares on the host system. However, validating the integrity of these VMs and their underlying hardware is critical to guaranteeing the confidentiality and security of the data that is processed.

For a detailed description of confidential VMs, read our  Learn about Red Hat Confidential Virtual Machines blog series.

VM attestation verifies the integrity of a confidential VM and its underlying platform components, including the CPU, firmware, and hypervisor. The attestation process might be initiated by the firmware or  initrd .

From a trust perspective, you need assurance that the VM you just created on a public cloud is really a CVM with an operating system of your choice. In particular, you need to make sure that the host hasn’t started a non-confidential VM with a specially crafted guest operating system to steal your secrets instead.

The following diagram shows the overall architecture for VM attestation: 

attestation-services-solution-image11

  • The CVM can run over a KVM hypervisor, some other hypervisor on bare metal or on a public cloud provider infrastructure.
  • The AA works with the Trustee AS.

Here is a list of Trustee and guest components being used:

Attestation for a confidential containers workload

Moving from the VM level attestation to a container level attestation, let’s focus on container workload the user wants to run in a secure manner protected from the host.

Attestation for confidential containers verifies the container runtime stack running in the confidential environment. This includes  kata-agent , supporting services like  agent-protocol-forwarder ,  process-user-data , open policy agent, and default policies that are needed to run the container.

If the confidential containers are using the VM trusted execution environment, then the attestation includes attestation of the VM followed by attestation of the container runtime components. This diagram shows the overall architecture for confidential container attestation: 

attestation-services-solution-image12

  • Peer-pods are used for running confidential containers over VMs (on-prem and public cloud). For additional details, read  Deploying confidential containers on the public cloud
  • The trustee model is used twice in this case to attest the CVM and then attest the confidential container runtime components

Here's a list of Trustee and guest components being used:

Attestation to retrieve container image signing or decryption keys

This use case is specific to obtaining the key for signature verification of a signed container image or obtaining the decryption key for encrypted images. For example, you might use encrypted container images to ship proprietary or sensitive code, such as AI models.

If the confidential containers are using the VM trusted execution environment, then the attestation process begins with VM attestation to confirm the integrity of the underlying execution environment. Once the VM's trustworthiness is established, container attestation proceeds, confirming the authenticity and integrity of the container runtime components. After a successful attestation, the container runtime requests the key from the Key Broker Service (KBS) for signature verification or decryption of the container images before starting the application.

The following diagram shows the overall architecture for retrieving the container image signing or decryption keys:

attestation-services-solution-image13

The attestation process is similar to attesting a confidential container workload, with the extra step of CDH retrieving the signing or decryption key that gets used by the kata-agent for signature verification or decrypting the container image.

This is a list of Trustee and guest components being used:

Attestation for releasing application secrets

This use case is specific to obtaining the key used by the workload. An example use case for obtaining the key is  Data Clean Rooms . 

A number of organizations want to analyze data without compromising the privacy of individuals whose data is being analyzed (a joint bank fraud detection effort, for example). They're required to create a shared secured environment for data leaving the boundaries of those individuals. They would also want that environment to run in the cloud at scale. This can be accomplished by a secure key release where the data decryption key is only released to a specific TEE based on attestation.

The following diagram shows the idea: 

attestation-services-solution-image14

If the confidential containers are using the VM trusted execution environment, then the attestation process begins with VM attestation to ensure the integrity of the underlying execution environment. Once the VM's  trustworthiness is established, container attestation proceeds, confirming the authenticity and integrity of the container runtime components. After a successful attestation, the container runtime starts the application.

The application then starts another attestation sequence to request the application secret from the Key Broker Service (KBS).  Confidential Data Hub (CDH) is used to request the application secret from the KBS by initiating an attestation sequence to prove the trustworthiness of the environment.

The following diagram shows the additional step of obtaining the application secret:

attestation-services-solution-image15

  • The attestation process is similar to attesting a confidential container workload, with the extra step of CDH retrieving the application secrets and providing it to the application
  • If the container images are signed or encrypted, then first the signing or decryption key is fetched (as described in the previous use case), followed by the application secret retrieval by CDH

Trustee project and confidential computing

In this blog we have introduced the Trustee project which is part of the  confidential containers CNCF initiative and includes a number of services providing attestation capabilities for containers, VMs, shared keys and more.

We’ve covered the IETF RATS model, reviewed the Trustee components and showed the mapping between Trustee and the RATS model. We’ve also reviewed a number of use cases requiring attestation and presented how the Trustee components are used for those purposes.

In future blogs, we'll dive deeper into the Trustee projects looking at the technical details and hands on instructions on how to try out things. 

About the authors

Ariel Adam author photo

Software Engineering Manager

Pradipta Banerjee, Senior Principal Software Engineer, Red Hat

Pradipta Banerjee

Senior Principal Software Engineer

Pradipta is working in the area of confidential containers to enhance the privacy and security of container workloads running in the public cloud. He is one of the project maintainers of the CNCF confidential containers project.  

  • Red Hat Enterprise Linux
  • Red Hat OpenShift
  • Red Hat Ansible Automation Platform
  • Cloud services
  • See all products
  • Developer resources
  • Customer support
  • Red Hat value calculator

Try, buy, & sell

  • Product trial center
  • Red Hat Marketplace
  • Red Hat Store
  • Buy online (Japan)

Communicate

  • Contact sales
  • Contact customer service
  • Contact training
  • About Red Hat

We’re the world’s leading provider of enterprise open source solutions—including Linux, cloud, container, and Kubernetes. We deliver hardened solutions that make it easier for enterprises to work across platforms and environments, from the core datacenter to the network edge.

Red Hat legal and privacy links

  • Contact Red Hat
  • Red Hat Blog
  • Diversity, equity, and inclusion
  • Cool Stuff Store
  • Red Hat Summit
  • Privacy statement
  • Terms of use
  • All policies and guidelines
  • Digital accessibility
  • FanNation FanNation FanNation
  • SI.COM SI.COM SI.COM
  • SI SWIMSUIT SI SWIMSUIT SI SWIMSUIT
  • SI Sportsbook SI Sportsbook SI Sportsbook
  • SI Tickets SI Tickets SI Tickets
  • SI Showcase SI Showcase SI Showcase
  • SI Resorts SI Resorts SI Resorts

Sep 9, 2023; Los Angeles:  USC's Zachariah Branch scores on a 50-yard punt return in the first half against Stanford.

© Kirby Lee-USA TODAY Sports

The Jet Award Comes With a Surprise

This year's trophy presentation will be missing a key component

  • Author: Dan McGlynn

In this story:

Johnny "The Jet" Rodgers had an amazing career at Nebraska from 1970-'72 as a wide receiver, punt and kick returner, and running back.  By the time he finished his Husker career, Rodgers had amassed 1,515 punt return yards for seven touchdowns.  He added 847 yards in kickoff returns and one TD, 2,479 receiving yards and 25 TDs, and 745 rushing yards with 11 more TDs.  Not surprising, Johnny ended up winning the Heisman in 1972.

But for well over a century of college football, returners were never given any kind of formal postseason recognition.

Since 1935 there has been the Heisman Trophy which honored the nation's best football player.  Later came the Mackey Award (best tight end), the Butkus Award (best linebacker), the Biletnikoff Award (best receiver), the Outland Award (best lineman), the Rimington Award (best center), Chuck Bednarik (best defensive player), Doak Walker (best running back), Maxwell Award (best all around player), Davey O'Brien (best quarterback) and the Ray Guy Award (best punter).

But thanks to Johnny Rodgers (and others), that all ended in 2012 with the creation of The Jet Award.  The honor is aptly named after Johnny "The Jet" Rodgers.  Maybe I'm a little biased, but I think JR "Superstar" is the best college returner ever.  Period.

Thursday night April 4th, the annual Jet Award event will take place at Baxter Arena in Omaha.

Larry The Cable Guy will be the special guest for the event. The keynote speaker will be former Chadron State College and NFL running back Danny Woodhead.

This year's Jet Award winner goes to Zachariah Branch, a freshman wide receiver from the University of Southern California.

I spoke with Rodgers over the weekend.  When I asked him when Branch was arriving in Omaha, he said Branch was not going to be there.  It turns out that Branch's coach, Lincoln Riley, won't let Zachariah attend because Riley doesn't want Branch to miss any spring football practice.

Huh?  

Why wouldn't a head coach want one of his best players to be honored at an event that would bring national attention to the USC football program?

More importantly, what kind of a college football player would want to play for a coach like Riley?

Makes no sense.

How 'Bout Them Huskers

Will and I talk about March Madness (and March Sadness for Nebraska basketball fans).  We look at Husker spring football practice as well as check up on Husker baseball and softball.  This week's Jet Award also gets our attention. Follow this link to listen.

Latest Cornhuskers News

New Mexico Lobos guard Jaelen House (10) looks to pass against the Wyoming Cowboys during the second half at Arena-Auditorium in Laramie, Wyoming, on Feb. 6, 2024.

Best Bets for Friday’s Round of 64 NCAA Tournament Games

_BSBvsNDSU0320-02

Gallery: Walsh Pitches Nebraska to 3-1 Win over NDSU

Jamarques Lawrence

How to Watch: Nebraska Men's Basketball vs. Texas A&M

A basketball displaying the March Madness logo enter the basket before the game between the USC Trojans and the Michigan State Spartans at Nationwide Arena.

NCAA Tournament 2024: Complete Schedule, Tip-Off Times, Locations, TV, Point Spreads

A general overall view of the NCAA Womens Basketball Final Four National Championship logo at center court at American Airlines Center.

NCAA Women's Basketball Tournament 2024: Complete Schedule, Tip-Off Times, Locations, TV, Point Spreads

IMAGES

  1. Container vs. Presentation Components

    presentation component vs container component

  2. Difference between component and container in react redux

    presentation component vs container component

  3. Step 12

    presentation component vs container component

  4. Learn about Presentational and Container components in React

    presentation component vs container component

  5. React: Presentational vs Container Components

    presentation component vs container component

  6. Presentational And Container Components In React

    presentation component vs container component

VIDEO

  1. Share Component Container on Specific Pages

  2. Key Component of Sales Presentation #salespresentation #needsidentification

  3. Key Component of Sales Presentation #salespresentation #closing

  4. Difference Between Azure Virtual Machine & Container Instances

  5. React CONTAINER vs COMPONENT

  6. Key Component of Sales Presentation #salespresentation #agenda #needsidentification

COMMENTS

  1. 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.

  2. 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 ...

  3. React Presentational vs. Container components: Which to choose?

    When building complex React applications, it's important to organize components in a way that maximizes code reusability and maintainability. One common approach is to use presentational and container components. Presentational components are responsible for rendering UI elements, while container components handle data and application logic. By separating these concerns, we can create a clear ...

  4. 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 ...

  5. Mastering React Patterns: Presentational and Container Components

    Container components handle the logic and state management of a React application. They orchestrate the interaction between Presentational components and manage the flow of data. Key characteristics of Container components include: Focus on the functionality and behavior of the application. Render Presentational components and pass them data ...

  6. ReactJS Container and Presentational Pattern in Components

    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 ...

  7. Presentation and Container Components

    Follow the React pattern of container/presentation components by refactoring the code and tests. React encourages a separation of concerns. UI components, aka presentation components, aka dumb components, are created by the bushel and managed by container components, aka smart components. The container maintains state, logic, and passes things ...

  8. React: Presentational vs Container Components

    In React components are often divided into 2 big buckets: presentational components and container components. Each of those have their unique characteristics. Presentational components are mostly concerned with generating some markup to be outputted. They don't manage any kind of state, except for state related to the presentation.

  9. An Overview of Presentational and Container Component Pattern

    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.

  10. Unlocking React's Power: Presentational vs. 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 ...

  11. Container vs Presentational Components in React

    3. The main thing to keep in mind is that container components and presentational components go together when setting up a React app component hierarchy. React apps will almost always need some ...

  12. What is presentational components vs container components in ...

    If we mix up presentational components with container components then the opportunity to simply use a "dumb" component to render something as simple as an image holder or text holder is lost.

  13. reactjs

    Presentational - no state, have no dependencies on the rest of the app, handle how things look. Container - usually has state, call redux actions, handle how things work. Full comparison here: Presentational and Container Components. edited Feb 21, 2018 at 8:23. answered Feb 21, 2018 at 8:18.

  14. Container vs. Presentation Components

    One of the fundamental concepts of component architecture in Angular applications is to find the right balance between container and presentation components. Let's define what those are: Presentation components are reusable, simple pieces of UI. Think buttons, dialogs, cards, nav bars, etc. Container components are the exact opposite: They ...

  15. Using Presentational and Container Components with Redux

    In React, a presentational component is a component that just renders HTML. The component's only function is presentational markup. In a Redux-powered app, a presentational component does not interact with the Redux store. The presentational component accepts props from a container component. The container component specifies the data a ...

  16. 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.

  17. 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

  18. Angular Architecture: Container vs Presentational Components Pitfalls

    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 ...

  19. Redux Presentational Components Vs Container Component

    Container Components. Are concerned with how things work. Responsible for providing data to presentational components via properties. Also responsible for handling state changes triggered inside a presentation component via callback properties. These state changes are often done via dispatching an action.

  20. Presentational VS Containers

    Presentational Components vs Container Components. When writing code in React or React Native, we often wonder how to structure our code so that it makes our life much easier when handling state changes, data flow and renders, etc. There is a pattern which helps in organizing React based applications - splitting the components into ...

  21. what is presentational component or container component in redux

    In the above example App in itself is a presentation component along with a smart component as it handles user interaction of incrementing and showing count. However ContainerApp is a component that is connected to redux store making use of presentational App component and is thus a container.

  22. Understanding the Difference between Containers and Components ...

    Components focus on defining the user interface and presentation logic, while containers handle the management of state and business logic. Roles and responsibilities of containers and components ...

  23. containerd vs. Docker

    A key component of containerd's robustness is its default use of Open Container Initiative (OCI)-compliant runtimes. By using runtimes such as runc (a lower-level container runtime), containerd ensures standardization and interoperability in containerized environments. It also efficiently deals with core operations in the container life cycle ...

  24. Introducing Confidential Containers Trustee: Attestation Services

    Once the VM's trustworthiness is established, container attestation proceeds, confirming the authenticity and integrity of the container runtime components. After a successful attestation, the container runtime requests the key from the Key Broker Service (KBS) for signature verification or decryption of the container images before starting the ...

  25. The Jet Award Comes With a Surprise

    USC Trojans. Johnny "The Jet" Rodgers had an amazing career at Nebraska from 1970-'72 as a wide receiver, punt and kick returner, and running back. By the time he finished his Husker career ...