gyanguide interview materials
Design Patterns

MERN Stack Mostly Uses Design Pattern

Frontend (React)

1. Component Pattern

Component Pattern is the foundation of React applications. In this pattern, the UI is divided into small reusable pieces called components. Each component manages its own structure, styling, and logic independently. Components can be functional or class-based, though modern React mainly uses functional components with hooks. This approach helps developers build complex applications by combining smaller UI blocks together.

For example, a job portal application may contain separate components for Navbar, JobCard, Footer, Sidebar, and LoginForm. These components can be reused across multiple pages, reducing duplicate code and improving maintainability. Component Pattern also supports scalability because updates to one component do not affect the entire application unnecessarily.


2. Custom Hook Pattern

Custom Hook Pattern allows developers to extract reusable logic from React components into separate functions. A custom hook is simply a JavaScript function that uses React hooks internally and starts with the word use. This pattern helps avoid code duplication and keeps components clean and readable.

For example, instead of writing API fetching logic repeatedly inside multiple components, developers can create a custom hook like useFetchJobs() or useAuth(). These hooks can manage API calls, loading states, and error handling centrally. Custom hooks improve code reusability, maintainability, and separation of concerns in large React applications.


3. HOC (Higher Order Component) Pattern

A Higher Order Component is a function that takes a component as input and returns an enhanced component with additional functionality. HOCs are commonly used to share reusable logic such as authentication, permissions, analytics tracking, or loading handling across multiple components.

For example, an authentication HOC can check whether a user is logged in before rendering a protected page. Instead of repeating login verification logic in every component, the HOC wraps the component and handles authentication centrally. This pattern promotes reusable logic and cleaner component structures in React applications.


4. Context Provider Pattern

Context Provider Pattern is used for global state management in React applications. It allows data to be shared across multiple components without passing props manually through every level of the component tree. React Context API provides a Provider component that stores and distributes shared state.

For example, authentication details like logged-in user information, theme settings, or language preferences can be managed globally using Context Provider Pattern. This pattern reduces prop drilling and simplifies state sharing between components. It is especially useful for medium-sized applications where Redux may feel too complex.


Backend (Node/Express)

5. MVC (Model View Controller)

MVC Pattern separates application logic into three layers: Model, View, and Controller. The Model handles database operations, the View manages responses or UI, and the Controller processes incoming requests and coordinates between models and views. In Express.js, controllers usually contain API handling logic.

For example, in a recruitment portal, the JobController handles API requests, the JobModel interacts with MongoDB, and the frontend React application acts as the View. MVC improves code organization, scalability, and maintainability by separating responsibilities clearly between application layers.


6. Middleware Pattern

Middleware Pattern is one of the core concepts of Express.js. Middleware functions execute sequentially between the request and response cycle. Each middleware can modify requests, validate data, authenticate users, log activity, or terminate the request early if needed.

For example, before accessing a protected API, a JWT authentication middleware verifies the user token. Another middleware may validate request data before passing control to the final controller. Middleware Pattern improves modularity because each middleware handles one specific responsibility independently.


7. Repository Pattern

Repository Pattern creates a separate layer for handling database operations. Instead of directly writing MongoDB queries inside controllers, database-related logic is moved into repository files or classes. Controllers and services communicate with repositories to access data.

For example, a UserRepository may contain methods like createUser(), findByEmail(), and updateProfile(). This pattern improves code maintainability because database logic remains centralized. It also makes testing easier since repositories can be mocked independently during unit testing.


8. Service Layer Pattern

Service Layer Pattern stores business logic inside dedicated service files instead of controllers. Controllers remain lightweight and mainly handle request and response management, while services perform calculations, validations, workflows, and business rules.

For example, during user registration, the UserService may handle password encryption, email verification, OTP generation, and database communication. This pattern improves reusability and maintainability because business logic remains centralized and can be reused across multiple controllers or APIs.


9. Singleton Pattern

Singleton Pattern ensures only one instance of a particular object exists during the entire application lifecycle. In Node.js applications, this pattern is commonly used for MongoDB database connections, configuration managers, and logger services.

For example, creating multiple MongoDB connections for every API request can waste memory and reduce performance. Instead, a single database connection instance is created and shared throughout the application. Singleton Pattern improves performance, consistency, and resource management.


Database

10. Repository Pattern

In database architecture, Repository Pattern acts as an abstraction layer between the application and database. It hides direct database operations from the business layer and provides clean methods for data manipulation.

For example, instead of writing raw MongoDB queries inside controllers, methods like getAllJobs() or saveCandidate() are placed inside repositories. This improves maintainability and makes it easier to migrate databases in the future without affecting business logic significantly.


11. Data Mapper Pattern

Data Mapper Pattern separates in-memory objects from database tables or collections. A mapper transfers data between objects and the database while keeping business logic independent from persistence logic.

In MongoDB ODM libraries like Mongoose, schemas and models act similarly to data mappers. This pattern improves flexibility because application objects do not depend directly on database structures. It also supports cleaner domain-driven application architecture.


Microservices

12. API Gateway Pattern

API Gateway Pattern provides a single entry point for all client requests in a microservices architecture. Instead of clients directly communicating with multiple services, requests go through the API Gateway, which routes them appropriately.

For example, an e-commerce application may have separate services for payments, authentication, inventory, and notifications. The API Gateway handles authentication, rate limiting, routing, caching, and logging centrally. This pattern simplifies frontend communication and improves security and scalability.


13. Pub/Sub Pattern

Pub/Sub (Publish Subscribe) Pattern enables asynchronous communication between services. Publishers send messages to a channel without knowing who receives them, while subscribers listen for specific events and process them independently.

For example, when an order is placed, the Order Service publishes an event. Notification, Inventory, and Billing services subscribe to the event and perform their own operations automatically. Pub/Sub improves scalability, loose coupling, and fault tolerance in distributed systems.


14. Circuit Breaker Pattern

Circuit Breaker Pattern protects applications from cascading failures in distributed systems. If a service repeatedly fails, the circuit breaker temporarily blocks further requests to that service instead of continuously retrying failed operations.

For example, if a payment service becomes unavailable, the circuit breaker stops sending requests temporarily and returns fallback responses. This prevents system overload and improves application stability. After a cooldown period, the system checks whether the failed service has recovered.


15. Event Driven Architecture

Event Driven Architecture is a software architecture style where services communicate through events instead of direct synchronous calls. When an action occurs, an event is generated and other services react to it independently.

For example, in a recruitment platform, when a candidate applies for a job, an event can trigger email notifications, interview scheduling, analytics updates, and CRM integration automatically. Event-driven systems improve scalability, flexibility, and asynchronous processing in modern cloud-native applications.