How-To Geek

What are presentational and container components in react.

4

Your changes have been saved

Email is sent

Email has already been sent

Please verify your email address.

You’ve reached your account maximum for followed topics.

Learn Python Basics: Let's Build A Simple Expense Tracker

How to switch from google to proton, google pixel’s new recorder app is a hit, quick links, is there any state, looking at examples, characteristics of each type, advantages of separating presentational and container components.

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

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

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

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

Here's a simple presentational component:

import React from "react";

class Presentational extends React.Component {

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

export default Presentational;

The component is extremely simple. It renders a single

tag which displays text passed into the component via its

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

class Container extends React.Component {

constructor(props) {

super(props);

this.state = {

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

componentDidMount() {

setInterval(() => {

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

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

export default Container;

The container component's

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

Each second, the container component calls

to update the

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

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

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

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

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

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

A container component's

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

Here's how this looks in practice:

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

<div>

<h1>{title}</h1>

<p>{body}</p>

</div>

class BlogPostComponent extends React.Component {

fetch("/blog-post.json")

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

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

title={this.state.blog.headline}

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

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

component for rendering.

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

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

In a real codebase,

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

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

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

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

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

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

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

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

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

  • Programming

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: Presentational vs Container Components

New Courses Coming Soon

Join the waiting lists

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
  • CODING BOOTCAMP cohort course - next edition in 2025
  • THE VALLEY OF CODE your web development manual
  • BOOKS 16 coding ebooks you can download for free on JS Python C PHP and lots more
  • Interesting links collection
  • Follow me on X

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 .

Read more posts .

If this article was helpful, share it .

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

Leveling Up With React: Container Components

Avatar of Brad Westfall

DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!

This tutorial is the second of a three-part series on React by Brad Westfall . This series is all about going beyond basic React skills and building bigger things, like entire Single Page Applications (SPAs). This article picks up where the last article, on React Router, left off.

Article Series:

  • React Router
  • Container Components (You are here!)

In the first article , we created routes and views. In this tutorial, we’re going to explore a new concept in which components don’t create views, but rather facilitate the ones that do. There is code to follow along with at GitHub , if you like to dive right into code.

We’ll also be introducing data to our application. If you’re familiar with with any sort of component-design or MVC patterns, you probably know that it’s generally considered poor-practice to mix your views with application behavior. In other words, while views need to receive data to render it, they shouldn’t know where the data came from, how it changes, or how to create it.

Fetching data with Ajax

As an example of a poor practice, let’s expand on our UserList component from the previous tutorial to handle its own data fetching:

If you need a more detailed/beginner explanation of what this component is doing, see this explanation .

Why is the example less than ideal?. To start, we’ve broken the rule of mixing “behavior” with “how to render the view” — the two things that should stay separate.

To be clear, there’s nothing wrong with using getInitialState to initialize component state, and there’s nothing wrong with conducting an Ajax request from componentDidMount (although we should probably abstract the actual call out to other functions). The problem is that we’re doing these things together in the same component where the view is stored. This tight-coupling makes the application more rigid and WET . What if you need to fetch a list of users elsewhere too? The action of fetching users is tied down to this view, so it’s not reusable.

The second problem is that we’re using jQuery for the Ajax call. Sure, jQuery has many nice features, but most of them deal with DOM rendering and React has its own way of doing this. As for jQuery’s non-DOM features like Ajax, chances are you can find lots of alternatives that are more single-feature focused.

One of those alternatives is Axios , a promise-based Ajax tool that’s very similar (in terms of API) to jQuery’s promise-based Ajax features. How similar are they?

For the remaining examples, we’ll continue to use Axios. Other similar tools include got , fetch , and SuperAgent .

Props and State

Before we get into Container and Presentational Components, we need to clear up something about props and state.

Props and state are somewhat related in the sense that they both “model” data for React components. Both of them can be passed down from parent to child components. However, the props and state of a parent component will become just props to their child component.

As an example, let’s say ComponentA passes some of its props and state to its child, ComponentB . The render method of ComponentA might look like this:

Even though foo is “state” on the parent, it will become a “prop” on the child ComponentB . The attribute for bar also becomes a prop on the child component because all data passed from parent to child will become props in the child. This example shows how a method from ComponentB can access foo and bar as props:

In the Fetching Data with Ajax example, data received from Ajax is set as the component’s state. The example doesn’t have child components, but you can imagine if it did, the state would “flow” down from parent to child as props.

To understand state better, see the React Documentation . From here on, this tutorial will refer to the data that changes over time, as “state”.

It’s time to break up

In the Fetching Data with Ajax example, we created a problem. Our UserList component works but it’s trying to do too many things. To solve the problem, let’s break the UserList into two components that each serve a different role. The two component types will be conceptually called Container Components and Presentational Components , a.k.a. “smart” and “dumb” components.

In short, Container Components source the data and deal with state. State is then passed to Presentational Components as props and is then rendered into views.

The terms “smart” vs “dumb” components are going away in the community. I’m only making reference to them here in case you read about them in older articles, so you’ll know they’re the same concept as Container vs Presentational.

Presentational Components

You may not know it, but you’ve already seen Presentation Components before in this tutorial series. Just imagine how the UserList component looked before it was managing its own state:

It’s not exactly the same as before, but it is a Presentational Component. The big difference between it and the original is that this one iterates over user data to create list-items, and receives the user data via props.

Presentational Components are “dumb” in the sense that they have no idea how the props they received came to be. They have no idea about state.

Presentational Components should never change the prop data itself. In fact, any component that receives props should consider that data immutable and owned by the parent. While the Presentational Component shouldn’t change the meaningfulness of the data in the prop, it can format the data for the view (such as turning a Unix timestamp into a something more human readable).

In React, events are attached directly to the view with attributes like onClick . However, one might wonder how events work since Presentational Components aren’t supposed to change the props. For that, we have a whole section on events below.

When creating DOM nodes in a loop, the key attribute is required to be something unique (relative to its siblings). Note that this is only for the highest level DOM node — the <li> in this case.

Also, if the nested return looks funky to you, consider another approach which does the same thing by splitting the creation of a list item into its own function:

Container Components

Container Components are almost always the parents of Presentational Components. In a way, they serve as a intermediary between Presentational Components and the rest of the application. They’re also called “smart” components because they’re aware of the application as a whole.

Since Container and Presentational Components need to have different names, we’ll call this one UserListContainer to avoid confusion:

For brevity, these examples have been leaving out require() and module.exports statements. But in this case, it’s important to show that Container Components pull in their respective Presentational Components as a direct dependency. For completeness, this example shows all the requires which would be necessary.

Container Components can be created just like any other React component. They also have a render methods just like any other component, they just don’t create anything to render themselves. Instead, they return the result of the Presentational Component.

A quick note on ES6 Arrow Functions: You may notice the classic var _this = this trick needed for the example above. ES6 Arrow functions , besides having shorter syntax, have other benefits which alleviate the need for this trick. To allow you to focus on just learning React, this tutorial avoids ES6 syntax in favor of the older ES5 syntax. However, the GitHub guide for this series makes heavy use of ES6 and it has some explanations in its README files.

So far, we’ve shown how state can be passed from Container to Presentational Components, but what about behavior? Events fall into the category of behavior and they oftentimes need to mutate data. Events in React are attached at the view level. For separation of concerns, this can cause a problem in our Presentational Components if we create event functions where the view is.

To elaborate, let’s start by adding an event to our Presentational Component (a <button> you can click) directly to identify problems:

This would technically work, but it’s not a good idea. Chances are, the event is going to need to change data, and data which changes should be stored as state — something the Presentational Component should not be aware of.

In our example, the state change would be the user’s “activeness”, but you can make up any functions you want to tie to onClick .

A better solution is to pass functionality from the Container Component into the Presentational Component as a prop like this:

The onClick attribute is required to be where the view is — at the Presentational Component. However, the function it calls has been moved to the parent Container Component. This is better because the Container Component deals with state.

If the parent function happens to change the state, then the state change will cause a re-render on the parent function which in turn will update the child component. This happens automatically in React.

Here is a demo which shows how the event on the Container Component can change state which will automatically update the Presentational Component:

See the Pen React Container Component Demo by Brad Westfall ( @bradwestfall ) on CodePen .

Take note of how this example deals with immutable data and makes use of the .bind() method

Using Container Components with the Router

The router should no longer use UserList directly. Instead, it will use UserListContainer directly, which in turn will use UserList . Ultimately, UserListContainer returns the result of UserList , so the router will still receive what it needs.

Data Flow and the Spread Operator

In React, the concept of props being passed from parent components down to child components is called flow. The examples so far have only shown simple parent-child relationships, but in a real application there could be many nested components. Imagine data flowing from high-level parent components down through many child components via state and props. This is a fundamental concept in React and is important to keep in mind as we move forward into the next tutorial on Redux.

ES6 has a new spread operator which is very useful. React has adopted a similar syntax to JSX. This really helps React with how data flows via props. The GitHub guide for this tutorial uses it too, so be sure to read the guide documentation on this feature.

Stateless Functional Components

As of React 0.14 (released in late 2015), there is a new feature for creating stateless (Presentational) components even easier. The new feature is called Stateless Functional Components

By now you’ve probably noticed that as you separate your Container and Presentational Components, many of your Presentational ones just have a render method. In these cases, React now allows the component to be written as a single function:

You can clearly see that the new way is more compact. But remember, this is only an option for components that just need a render method.

With the new Stateless Functional way, the function accepts an argument for props . This means it doesn’t need to use this to access props.

Here is a very good Egghead.io video on Stateless Functional Components.

As you’ve probably seen so far, React doesn’t resemble traditional MVC. Often times React is referred to as “just the view layer”. The problem I have with this statement is that it’s too easy for React beginners to believe that React should fit into their familiarity with traditional MVC, as if it’s meant to to be used with traditional controllers and models brought in from third-party.

While it is true that React doesn’t have “traditional controllers”, it does provide a means to separate views and behavior in its own special way. I believe that Container Components serve the same fundamental purpose that a controller would serve in traditional MVC.

As for models, I’ve seen people use Backbone models with React and I’m sure they have all kinds of opinions on whether that worked out well for them. But I’m not convinced that traditional models are the way to go in React. React wants to flow data in a way that just doesn’t lend itself well to how traditional models work. The Flux design pattern, created by Facebook , is a way to embrace React’s innate ability to flow data. In the next tutorial, we’ll cover Redux, a very popular Flux implementation and what I view as an alternative to traditional models.

Container Components are more of a concept and not an exact solution. The examples in this tutorial just are one way to do them. The concept though, is so well accepted that it’s even Facebook’s policy to use them within their teams — although they might use different terminology.

This tutorial was highly influenced by other articles on this topic. Be sure to look at this tutorial’s official GitHub guides for even more information and a working example of Container Components.

Great topic and great article — Looking forward to part 3!

In React, is it possible to get around this type of ugly state code?

According to the React docs, setState() performs a shallow merge. This means that the user object itself should remain the same, even though the reference to it is copied into a new state object. So, why not do this?

Based on my understanding, and some quick fiddling around in your CodePen, that should work fine, as it’s essentially exactly the same logic with a lot less code.

What are your thoughts?

Thanks Agop, great question. So what you’re actually doing is mutating this.state directly since user is a reference to this.state . See these docs https://facebook.github.io/react/docs/component-api.html . Read the warning section where it says “NEVER mutate this.state directly”.

I understand it looks simpler with how you did it, but state mutation is a big deal in React which we don’t get into deeply until the next article. I could have used more tools like lodash or Immutable.js to make my code look nicer, and still adhere to mutation best practices. But I was trying not to introduce more tools into the example. This was just the best way I could think of to do it using vanilla JS (albeit, Object.assign() is ES6)

Brad, using Object.assign() isn’t doing anything to prevent modifying the state. When you call Object.assign() , you end up with a shallow copy of this.state , which still references the same exact list of users (and thus, the same exact user objects).

You can confirm this with this code:

In the console, you’ll see:

So, you’re still modifying the same exact user object living in this.state , just through a new reference to it. You can further confirm by adding this after the code that toggles active :

Here’s a quick pen to demonstrate:

http://codepen.io/agop/pen/ONmJRK

Long story short, all of that code boils down to what I previously wrote:

If you want to truly avoid modifying the state itself, including any of its nested objects, you would need to perform a deep copy of this.state . And once we start talking about deep copies, we need to start talking about performance. What if we had 100 users? Are we going to create a deep copy of all 100 users, including all of their properties, just to update 1 property of 1 user?

So I had some lengthly Slack discussions with some JS friends and here’s the consensus. For one, we should never mutate this.state if we’re adhering to best practices, see my comment from before with the React docs. Secondly, you’re right about how I was using Object.assign() and the shallowness. What I should have done is:

And made a copy of just the user and not the whole state. Now the test of user === newUser is false. The problem now is that because the state is an array, it’s now difficult to “slice” in the newUser into it’s original spot. There are various techniques but remember I was trying to avoid new tools like lodash or any complexity that’s off-topic for the pen. One way to do it though is in this alternative codepen http://codepen.io/bradwestfall/pen/NNjWLR if one were to stick to no-new-tools and ES6. Also, again, it’s just one way.

For beginner’s sake though, I really just wanted a codepen that would demonstrate passing a function via props from parent to child. I didn’t mean to get into this immutability mess :) So I’ve updated the original pen to do it the very simple mutable way — with a disclaimer that it’s not technically best practice. While your way is even smaller code though, I find it to be confusing to beginners, and off-topic since again the purpose of the pen is to teach something else, and to do it right with immutability, we’d have to get into lots of other stuff which aren’t the purpose of the pen.

Further, if worried about performance, tools like Immutable.js and React’s own Immutability Helpers should serve you well http://facebook.github.io/react/docs/update.html

Brad, I was actually just about to write much of the same stuff, after digging further into React best practices, but you beat me to it. So, that’s right, neither of our original codes (which were identical in terms of what actually happened to the underlying state) adhered to best practices.

As you well know, and accurately described in your comments, your updated version doesn’t adhere to best practices either (new user object, but same users list). I would make some small tweaks that would keep the code simple for the article readers, while totally adhering to React immutability best practices:

http://codepen.io/agop/pen/grWbqx

We didn’t modify this.state or any of its nested properties, but we kept the code nice and concise (no ES6 usage, keeping it simple). This way you don’t have to get deep into the depths of React and Immutability, without showing a misleading example (let’s be honest, who’s going to read the comments and truly understand that the example is “almost” immutable?).

This also answers my own question about deep copies – we don’t need deep copies. We can reference existing objects, and we only need to create shallow copies of stuff that actually changes. As you mentioned in your comment, all of this can be simplified with React’s own immutability helpers, as well as stuff like Immutable-js, etc.

Thanks Agop, I think if anyone reads all this they’ll say the article was easy enough, but what is this immutable thing all about? – those who haven’t been exposed to it at least :) I think our conversation documents it enough for this article. The codepen’s comments actually have a link pointing to this conversation too. I think I’ll keep it as-is because of the main point of the pen being about something else. Thanks for all your feedback and the suggested code.

Brad, it’s your code, your article, and between you and I, we’re clearly both on the same page ;)

Still, I don’t see the purpose of leaving this in the article:

That’s literally dead code. It doesn’t do anything at all ( users[index] === user before the assignment anyways). It’s just confusing for the reader, and you’re the one that argued against confusing the reader (e.g. “Why is he assigning the user into same list at the same index?”, “Why is he passing the same list back into the state?”, etc.).

My code, from start to finish, including comments, is 16 lines, ES5-only, and very easy to understand, even without going into the “whys” of immutability in React. Your code, from start to finish, including comments, is 17 lines.

You say that you don’t want to get into immutability with this article, and that’s fine. Yet, your code has a 5-line comment block talking about how it doesn’t follow immutability best practices and links out to a huge discussion that would make absolutely 0 sense to someone new to React. My code doesn’t make any mention of immutability at all, it just follows it.

Long story short, I’m just trying to understand the thought process behind leaving code that doesn’t adhere to best practices in an article that is already in 5th position when you Google something like “react container components”. It’s frustrating to me to think that someone new to React is going to land on this article, see the example, quickly skip the big block of comments (come on, who reads giant blocks of comments in a CodePen?), and then right below the example, read:

Take note of how this example deals with immutable data

Sorry, I’ll end my rant now.

Thanks Agop, I’ll look at this later :) I’m wrapped up writing the Redux article this week along with some work stuff

Great topic and great articles so far! Looking forward to part 3 :)

Loving this series, Brad. I’d read both of the articles you referenced as inspiration, but the container vs. presentational concept didn’t really click for me until reading this. Thank you!

Thanks Kyle!

A huge, hearty thank you Brad! CSS-Tricks has helped me get better at my craft over the past few years. Your tutorials are easy to follow which I really like. Looking forward to Part 3! :)

Kind regards, Loraine Ortiz

Thanks Loraine

This blog post was featured in The React Newsletter #23. http://us4.campaign-archive2.com/?u=29c888baee9c05ccb614e1e92&id=4d59132d66

A very good introduction to React components!

I’ve elaborated this article using slightly different technics, would you be so kind to look into my pen: http://codepen.io/bluurn/pen/xVJNWw

Just wanted to know whether I am correct ( or not :) ).

Thank you very much!

In general it looks pretty good. I noticed the links don’t work though. One reason may be because you did quotes around the curlies <Link to="{'/users/' + user.id}">{user.name}</Link> . If an attribute is going to take dynamic parts from JS, then you don’t do the quotes around it. Also, I hope you read part three of this series too because you’ll see how state management is different with Redux – for a multiple component app. Thanks bluurn

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

Design Pattern

Container/Presentational Pattern

In 2015, Dan Abramov wrote an article titled “Presentational and Container Components” that changed the way many developers thought about component architecture in React. He introduced a pattern that separated components into two categories:

  • Presentational Components (or Dumb Components) : These are concerned with how things look. They don’t specify how the data is loaded or mutated but rather receive data and callbacks exclusively via props.
  • Container Components (or Smart Components) : These are concerned with how things work. They provide the data and behavior to presentational or other container components.

While this pattern was mainly associated with React, its fundamental principle was adopted and adapted in various forms across other libraries and frameworks.

Dan’s distinction offered a clearer and more scalable way to structure JavaScript applications. By clearly defining the responsibilities of different types of components, developers could ensure better reusability of the UI components (presentational) and logic (containers). The idea was that if we were to change how something looked (like a button’s design), we could do so without touching the logic of the app. Conversely, if we needed to change how data flowed or was processed, the presentational components would remain untouched, ensuring that the UI remained consistent.

However, with the emergence of hooks in React and the Composition API in Vue 3, the clear boundary between presentational and container components began to blur. Hooks and the Composition API began allowing developers to encapsulate and reuse state and logic without necessarily being confined to a class-based container component or the Options API. As a result, the container/presentational pattern isn’t as rigidly adhered to as it once was. With that being said, we’ll spend some time in this article discussing the pattern since it can still be helpful at certain times.

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

Browse dogs application

To follow the container/presentational pattern, we want to enforce the 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 of 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. To do so, we can create a DogImages component that receives the data through props and renders the data it receives.

The DogImages component can be regarded to be a presentational component. Presentational components are usually stateless: they do not contain their own component 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 to display it on the screen. We’ll call this container component DogImagesContainer .

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

This in a nutshell is the container/presentational pattern. When integrating with state management solutions like Pinia , the container components can be leveraged to interact directly with the store, fetching or mutating the state as needed. This allows the presentational components to remain pure and unaware of the broader application logic, focusing only on rendering the UI based on the props they receive.

Composables

Do read the Composables guide for a deep-dive into understanding composables.

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

Instead of having the data fetching logic in the DogImagesContainer component, we can create a composable 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.

With all the changes we’ve made, our app can be seen as below.

Composables 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 to wrap the presentational component within the container component.

Helpful Resources

  • Vue Composables | Patterns.dev

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

lulu_liu_c90f973e2f954d7f profile image

My Experience with SafeLine Community Edition WAF

Lulu - Sep 3

sheraz4194 profile image

Mastering Tailwind CSS: Overcome Styling Conflicts with Tailwind Merge and clsx

Sheraz Manzoor - Sep 3

johnrushx profile image

1417 Open Source alternatives to tools you pay for

John Rush - Sep 6

poornima545 profile image

Getting started with react

Poornima Gowda - Sep 3

DEV Community

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

  • React Course
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • Web Technology

Presentational and Container Components in React Redux

React Redux is a library that simplifies state management in React applications by providing a centralized store where data can be stored and accessed from any component. It helps keep your code organized and efficient, especially in large-scale projects where the managing state becomes more complex. With React Redux, you can easily connect your React components to the store and update the UI in response to changes in the application state.

Presentational Components :

  • These components are primarily concerned with how things look. They encapsulate the visual representation of your application’s UI.
  • They receive data and callbacks from their parent components via props, but they are not aware of where this data comes from or how it’s managed.
  • Presentational components are typically stateless functional components or simple class components with minimal logic.
  • Examples include buttons , form inputs , cards , and other UI elements.

Container Components :

  • These components are responsible for how things work. They interact with the Redux store and manage the application’s state and logic.
  • Container components are often connected to the Redux store using the connect function from R eact Redux , which allows them to access state and dispatch actions.
  • They handle data fetching, state updates, and dispatching actions in response to user interactions or other events.
  • Container components contain little to no markup or styling of their own, focusing solely on the application’s functionality.
  • Examples include pages, screens, and components that orchestrate the behavior of multiple presentational components.

Please Login to comment...

  • Web Technologies
  • WebTech-FAQs
  • Top Android Apps for 2024
  • Top Cell Phone Signal Boosters in 2024
  • Best Travel Apps (Paid & Free) in 2024
  • The Best Smart Home Devices for 2024
  • 15 Most Important Aptitude Topics For Placements [2024]

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

presentational vs container components

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 :

presentational vs container components

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

Collectives™ on Stack Overflow

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

Q&A for work

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

Get early access and see previews of new features.

react component vs container

I'm new to react and I'm trying to separate the component. Are the following examples containers or components? For me both are components but I'm not sure because they have Link tag and Route tag.

Ben Hare's user avatar

2 Answers 2

I think you may want to know the concept of presentational and container components in React. Your two examples both are presentational components, since they just use the props they receive to render their looks. They don't care how to get the correct props data. In contrast to presentational components, container components care about how things work. They should be responsible for the business logics while presentational components are only concerned about the UI logics of themselves. This is an detailed explanation.

Jason Xu's user avatar

  • And just as an addendum, your references to "component" or "container" map to these "presentation" and "container" components. –  Ben Hare Commented Jun 21, 2017 at 4:01

Component is part of the React API. A Component is a class or function that describes part of a React UI.

Container is an informal term for a React component that is connect-ed to a redux store. Containers receive Redux state updates and dispatch actions, and they usually don't render DOM elements; they delegate rendering to presentational child components.

Saad Bilal's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

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

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • What`s this? (Found among circulating tumor cells)
  • In which town of Europe (Germany ?) were this 2 photos taken during WWII?
  • An instructor is being added to co-teach a course for questionable reasons, against the course author's wishes—what can be done?
  • How do you tip cash when you don't have proper denomination or no cash at all?
  • Text wrapping in longtable not working
  • Are others allowed to use my copyrighted figures in theses, without asking?
  • Is my magic enough to keep a person without skin alive for a month?
  • What's the radius of Mars over Mount Olympus?
  • Conjugate elements in an extension
  • What is the term for the belief that significant events cannot have trivial causes?
  • Why didn't Air Force Ones have camouflage?
  • Does a party have to wait 1d4 hours to start a Short Rest if no healing is available and an ally is only stabilized?
  • Fusion September 2024: Where are we with respect to "engineering break even"?
  • Is the 2024 Ukrainian invasion of the Kursk region the first time since WW2 Russia was invaded?
  • When can the cat and mouse meet?
  • Why isn't a confidence level of anything >50% "good enough"?
  • Why is notation in logic so different from algebra?
  • Sylvester primes
  • Is it possible to recover from a graveyard spiral?
  • A seven letter *
  • What should I do if my student has quarrel with my collaborator
  • What should I consider when hiring a graphic designer to digitize my scientific plots?
  • An error in formula proposed by Riley et al to calculate the sample size
  • Etymology of 制度

presentational vs container components

IMAGES

  1. Presentational vs Container by Мария Крень on Prezi

    presentational vs container components

  2. Learn about Presentational and Container components in React

    presentational vs container components

  3. [Solved] Difference between component and container in

    presentational vs container components

  4. Presentational vs Container Component

    presentational vs container components

  5. React: Presentational vs Container Components

    presentational vs container components

  6. Presentational vs Container

    presentational vs container components

VIDEO

  1. 26. Presentational & Container Components

  2. [FER201m]Bài 16

  3. React and CodeCademy Day 12

  4. Difference Between Azure Virtual Machine & Container Instances

  5. 22. Presentational and Container Components

  6. Five Presentation 2010

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

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

  4. ReactJS Container and Presentational Pattern in Components

    Benefits of Container/Presentational Pattern. Creates pure functions. Separates render and fetching logic. Makes the components more reusable. Testing the components is easier. Disadvantages of Container/Presentational Pattern. It's alternatives perform better. Usage is decreased as we no longer need class components to create states.

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

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

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

    Container components; Presentational components; Container 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.

  8. Leveling Up With React: Container Components

    To solve the problem, let's break the UserList into two components that each serve a different role. The two component types will be conceptually called Container Components and Presentational Components, a.k.a. "smart" and "dumb" components. In short, Container Components source the data and deal with state.

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

  10. Container/Presentational Pattern

    To follow the container/presentational pattern, we want to enforce the 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 of the list of dog images. Container Components: Components that care about what ...

  11. React Design Patterns: Presentational and Container Components

    The term presentational and container components refers to a design pattern within React, where components are separated into two main buckets: presentationa...

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

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

    Both presentational components and containers can fall into either of those buckets. In my experience, presentational components tend to be stateless pure functions, and containers tend to be stateful pure classes. However this is not a rule but an observation, and I've seen the exact opposite cases that made sense in specific circumstances. ...

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

  15. Presentational and Container Components in React Redux

    Presentational components are typically stateless functional components or simple class components with minimal logic. Examples include buttons, form inputs, cards, and other UI elements. Container Components: These components are responsible for how things work. They interact with the Redux store and manage the application's state and logic.

  16. React Design Patterns: The Container/Presentational Pattern

    The Presentational Component. Presentational components are purely focused on the UI rendering logic. They receive data and callbacks as props from the container components and use them to render ...

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

  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

    2. Here is the summarized version of the differences inorder to understand easily, even though some of them are related to the above answer above, Container Components. 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. Container vs. Presentational Components in React Redux

    Presentational components deal with how things look — they are often child components of parent containers. They are not usually stateful. They are reusable. Container components deal with data ...

  21. Regarding Dan Abramov's update about Presentational and Container

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

  22. Container and Presentational Components in Angular

    By adopting Container and Presentational Components in your Angular applications, you can achieve a clean separation of concerns, leading to more maintainable, testable, and scalable code. However ...

  23. reactjs

    Component is part of the React API. A Component is a class or function that describes part of a React UI. Container is an informal term for a React component that is connect-ed to a redux store. Containers receive Redux state updates and dispatch actions, and they usually don't render DOM elements; they delegate rendering to presentational ...