Modern Frontend Architecture

From the archive: a general guide from February 2024, tidied and kept for reference.

Modern Frontend Architecture

Modern Frontend Architecture

Presentation Layer

React Vue Angular

State Management

Redux Pinia Context API

Services Layer

API Client Authentication Caching

State Management Patterns

Redux Pattern


// Action Types
const ADD_TODO = 'ADD_TODO';

// Action Creator
const addTodo = (text) => ({
    type: ADD_TODO,
    payload: { text }
});

// Reducer
const todoReducer = (state = [], action) => {
    switch (action.type) {
        case ADD_TODO:
            return [...state, action.payload];
        default:
            return state;
    }
};

// Store Usage
store.dispatch(addTodo('Learn Redux'));

This is the hand-written pattern. Current Redux code uses Redux Toolkit, whose createSlice generates the action types, action creators and reducer for you.

Context API Pattern


// Create Context
const TodoContext = React.createContext();

// Provider Component
const TodoProvider = ({ children }) => {
    const [todos, setTodos] = useState([]);

    const addTodo = (text) => {
        setTodos([...todos, { text }]);
    };

    return (
        <TodoContext.Provider value={{ todos, addTodo }}>
            {children}
        </TodoContext.Provider>
    );
};

Performance Optimization

Code Splitting


// Load a heavy route only when it is first rendered
import { lazy, Suspense } from 'react';

const Dashboard = lazy(() => import('./Dashboard'));

function App() {
    return (
        <Suspense fallback={<p>Loading...</p>}>
            <Dashboard />
        </Suspense>
    );
}

Rendering and Assets

  • Memoize expensive components and values (React.memo, useMemo)
  • Virtualize long lists
  • Lazy-load images below the fold
  • Measure with the browser's performance tools before and after a change

Component Architecture

Atomic Components

Buttons Inputs Icons

Molecular Components

Forms Cards Navigation

Organisms

Headers Dashboards Features

Best Practices & Patterns

Code Organization


src/
├── components/
│   ├── atoms/
│   ├── molecules/
│   └── organisms/
├── hooks/
├── services/
├── store/
└── utils/

State Updates

  • Immutable updates
  • Single source of truth
  • Unidirectional data flow