Skip to content
Plurafy

React Design Patterns

A details explanation about different design patterns used with React.

Higher-Order Components (HOCs) are functions that take a component and return a new component with enhanced behavior or additional props. They are commonly used for code reuse, logic abstraction, and conditional rendering.

Example:

import React from "react";
function withLogger(WrappedComponent) {
return function LoggerComponent(props) {
console.log("Rendering", WrappedComponent.name);
return <WrappedComponent {...props} />;
};
}

Render props is a pattern where a component accepts a function as a prop, which it uses to determine what to render. This allows for greater flexibility and code reuse by enabling dynamic rendering based on the provided function.

Example:

import React, { useState } from "react";
function MouseTracker({ render }) {
const [position, setPosition] = useState({ x: 0, y: 0 });
const handleMouseMove = (event) => {
setPosition({ x: event.clientX, y: event.clientY });
};
return <div onMouseMove={handleMouseMove}>{render(position)}</div>;
}
function App() {
return (
<MouseTracker
render={({ x, y }) => (
<p>
Mouse position: ({x}, {y})
</p>
)}
/>
);
}

The container-presentational pattern separates components into two categories: container components, which handle state and logic, and presentational components, which focus on rendering UI based on props. This pattern promotes separation of concerns and makes components more reusable and easier to test.

Example:

import React, { useState } from "react";
function UserContainer() {
const [user, setUser] = useState({ name: "John Doe", age: 30 });
return <UserProfile user={user} />;
}
function UserProfile({ user }) {
return (
<div>
<p>Name: {user.name}</p>
<p>Age: {user.age}</p>
</div>
);
}

Compound components are a pattern where multiple components work together to manage state and behavior, while keeping the API flexible and declarative. This pattern allows you to create a parent component that manages the state and passes it down to its child components via context.

Example:

import { createContext, useContext, useState } from "react";
const TabsContext = createContext();
function Tabs({ children }) {
const [activeIndex, setActiveIndex] = useState(0);
return (
<TabsContext.Provider value={{ activeIndex, setActiveIndex }}>
{children}
</TabsContext.Provider>
);
}
function TabList({ children }) {
return <div>{children}</div>;
}
function Tab({ index, children }) {
const { activeIndex, setActiveIndex } = useContext(TabsContext);
return (
<button
onClick={() => setActiveIndex(index)}
style={{ fontWeight: activeIndex === index ? "bold" : "normal" }}
>
{children}
</button>
);
}
function TabPanels({ children }) {
const { activeIndex } = useContext(TabsContext);
return <div>{children[activeIndex]}</div>;
}

The hooks pattern involves creating custom hooks to encapsulate and reuse stateful logic across multiple components. This pattern promotes code reuse and separation of concerns by extracting complex logic from components into reusable functions.

Example:

import { useState, useEffect } from "react";
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return width;
}