React Pattern — Container/Presentational Pattern

Amber Fung
2 min readJul 30, 2024

--

Container/Presentational pattern is a React design pattern that separates the responsibility. The presentational component decides how the component looks and the container component determines how the component works.

Presentational component

The presentational component only cares about the UI it presents to the user. It usually receives the data through the props. Here is an example of a presentational component in implementing the button.

const Button = ({ onClick, children }) = {
return <button onClick={onClick}>{children}</button>;
};

export default Button;

Container component

The container component only cares about the logic that controls the presentational component. Data fetching and state management are usually processed in a container component. Let’s use an example to elaborate on how the container component works by importing the presentational buttons.

import React, { useState } from 'react';
import Button from './Button';

const ButtonCounter = () => {
const [count, setCount] = useState(0);

const handleClick = () => {
setCount((prev)=>prev+1);
};

return (
<div>
<Button label="Click me" onClick={handleClick} />
<p>You clicked {count} times</p>
</div>
);
};

export default ButtonCounter;

We import the button component and control he count state in ButtonCounter.

Pros

  • Separation of concern: Container/Presentational pattern assigns clear responsibility to the components. The presentational component focuses on how the components look and the container component focuses on how the components work.
  • Reusability: Since the presentational component only focuses on UI presentation, it can be reused by composing different business logic to make it become a complex component.

Conclusion

Container/Presentational pattern separates the functionality of the components and brings maintainability and reusability.

--

--

No responses yet