Hello developers!! While developing apps in React, I'm sure you have come across different use cases which cannot be easy to solve using the same older approach.
Each use cases demand a different pattern to solve the problem in the most optimised way and also made our code more scalable.
React provides different design patterns to solve common problems. The list of commonly used design patterns in React are:
Presentational & Container Component
Higher Order Components
Render Props
Compound Components
Hooks
Let's explore them one by one.
🎯 1. Presentational & Container Component
Each component in React has two parts: One is logic to handle your data and the other is displaying data on screen.
This pattern helps separate concerns by splitting components into two categories. Container components handle the logic and state management, while Presentational components focus on rendering the UI based on the provided props.
export const DisplayList = ({ patientRecord }) => {
return (
<ul>
{patientRecord.map((patient, id) => {
return <li key={id}>{patient}</li>;
})}
</ul>
);
};
Container components, on the other hand, keep track of the internal states and data-fetching logic and handles business logic.
export const PatientComponent = () => {
const [patientList, getPatientList] = React.useState([]);
React.useEffect(() => {
// Fetch data through an API and apply business logic
(async () => {
const response = await fetchPatientList();
setPatientList([...response]);
})()
}, []);
// provide data to presentational component to display
return <DisplayList patientRecord={patientList} />;
};
The container component passes the state and any required callbacks as props to the presentational component. The presentational component is responsible for rendering the UI based on the provided props, without worrying about the data fetching or business logic.
🎯 2. Higher Order Components
HOCs take one component as an input and give a newly created component with additional functionalities as an output. It allows you to reuse component logic by wrapping components with additional functionality.
By using HOCs, we can easily add common functionality to multiple components without duplicating code.
import React from 'react';
function withLogging(WrappedComponent) {
return function WithLogging(props) {
React.useEffect(() => {
console.log(`Component ${WrappedComponent.name} mounted`);
return () => {
console.log(`Component ${WrappedComponent.name} unmounted`);
};
}, []);
return <WrappedComponent {...props} />;
};
}
// Usage
const MyComponent = (props) => {
return <div>My Component</div>;
};
const EnhancedComponent = withLogger(MyComponent);
In the example above, withLogger
is a HOC that takes a component (WrappedComponent
) as input and returns a new component (WithLogger
). The returned component logs a message to the console when it mounts and unmounts.
To use the HOC, we wrap our original component MyComponent
with withLogger
, creating a new component EnhancedComponent
. The enhanced component has the same functionality as MyComponent
, but it also includes the logging behaviour defined in the HOC.
🎯 3. Render props
In this pattern, a component receives a function as a prop and uses that function to render its content.
import React from 'react';
const MouseTracker = (props) => {
const [position, setPosition] = React.useState({ x: 0, y: 0 });
const handleMouseMove = (event) => {
setPosition({ x: event.clientX, y: event.clientY });
};
return <div onMouseMove={handleMouseMove}>{props.renderPosition(position)}</div>;
};
// Usage
const DisplayMousePosition = () => (
<MouseTracker
renderPosition={({ x, y }) => (
<div>
Mouse position: {x}, {y}
</div>
)}
/>
);
A prop like renderPosition
is called a render prop because it is a prop that specifies how to render a piece of the user interface.
🎯 4. Compound Components
Compound components are a pattern used in React to create components that work together as a group, allowing users to customize and control the rendering of multiple related components.
It allows you to define a parent component that encapsulates the behaviour and state of child components, while still giving flexibility to users to determine the composition and appearance of the child components.
Let's consider a use case where you need to create a List component in React which looks something like an unordered list in native HTML or an Accordion component.
<List>
<ListItem>1</ListItem>
<ListItem>2</ListItem>
<ListItem>3</ListItem>
<ListItem>4</ListItem>
</List>
Now in this scenario, we need some of the states of the List component to be transferred to its child component i.e. ListItem. It can be implemented either by using the context API
or React.cloneElement
API.
Let's explore how to develop the same scenario using Context API.
const ListContext = React.createContext();
const { Provider } = ListContext;
// Parent Component
export const List = (props) => {
const { children, size } = props;
const sharedProp = { size }
return (
<Provider value={sharedProp}>
<ul>
{children}
</ul>
</Provider>
)
}
// Child Component
export const ListItem = (props) => {
const contextProp = React.useContext(ListContext);
const { size } = contextProp;
return (
<li className={size === 'medium' ? bg-primary : bg-secondary}>
{props.children}
</li>
)
}
// Usage
<List size='medium'>
<ListItem>Item 1</ListItem>
<ListItem>Item 2</ListItem>
<ListItem>Item 3</ListItem>
</List>
In the above example, React Context is created to share the prop size
between the parent (<List>) and child (<ListItem>) components. Also, the user has the flexibility to provide custom content inside each list item.
🎯 5. Hooks
Hooks are introduced in React Functional component as a replacement for Class components. There are multiple hooks available to manage states and different lifecycle methods of React.
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<Button onClick={() => setCount(count + 1)}></Button>
)
}
We can also create custom hooks to solve our specific use case and code reusability.
You can read about the most commonly used built-in react hooks here.
🎯 Wrap Up!!
That's all for this article. Thank you for your time!! Let's connect to learn and grow together. LinkedIn Twitter Instagram
Oldest comments (20)
Amazing!
Great Design Patterns. I like them.
From react components docs: "Class components are still supported by React, but we don’t recommend using them in new code."
Why are you making so much use of Class components?
I believe they're seen as bad practice, no?
Not really bad practice per say. Just that their use are discouraged and instead functional components should be used.
Deprecated as per React 18 and the new React docs.
I don't believe that class components deserve the bad rep.
I'm a big fan of classes and object oriented programming but I don't think classes are a good use case for react components.
Dan Abramov explains here how class components can lead to bugs which are avoided with functional components.
overreacted.io/how-are-function-co...
Furthermore, you can't use hooks in class components so you are limited to what libraries and other parts of your code base you can use if you mix and match between classes and functional components
Lol I use all of them but never heard that they are called this way.
Everyone uses all of these just they don't know
There's a difference between using a library that happens to still use class components and writing class components yourself though...
Few things to take into account:
const { Provider } = ListContext;
on every render, just move to outside of the component.@erickjth Thank you for your suggestions. I'll surely update the examples.
Class components... MY EYES 🤮
Thanks for article ,👏👏😃
@just-another-girl-w3 I'm glad you find it useful!!😃
Great article , please checkout this website refactoring.guru/design-patterns and tell me what’s the difference between patterns with those that you mentioned
THANKS A LOT!
Some comments have been hidden by the post's author - find out more