Jump to content

Featured Replies

Posted

You are reading Part 38 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 6]

Introduction

JavaScript frameworks like React, Vue, and Angular provide powerful abstractions that simplify web development. But how do these frameworks work internally? This article explores the core concepts behind modern JavaScript frameworks, including virtual DOM, reactivity, component-based architecture, and state management. By understanding these principles, you can start building your own lightweight framework.

1. Core Concepts of JavaScript Frameworks

Most modern JavaScript frameworks share these fundamental concepts:

  • Component-Based ArchitectureUI is broken into reusable components.

  • Virtual DOM – Efficient updates by diffing and patching only changed parts.

  • Reactivity – Automatic UI updates when data changes.

  • State Management – Centralized management of application state.

  • Event Handling – Simplifies handling user interactions.

2. Creating a Simple JavaScript Framework

To understand how frameworks work, let's build a basic UI rendering library that handles components, state, and rendering.

Step 1: Implementing a Basic Virtual DOM

The Virtual DOM is a lightweight representation of the actual DOM, allowing efficient updates.

function createElement(type, props, ...children) {
    return { type, props: props || {}, children };
}

Step 2: Rendering Virtual DOM to Real DOM

function render(vdom, container) {
    if (typeof vdom === "string") {
        container.appendChild(document.createTextNode(vdom));
        return;
    }
    const el = document.createElement(vdom.type);
    Object.entries(vdom.props).forEach(([key, value]) => el.setAttribute(key, value));
    vdom.children.forEach(child => render(child, el));
    container.appendChild(el);
}

Example Usage:

const vApp = createElement("div", { id: "app" },
    createElement("h1", null, "Hello, Framework!"),
    createElement("button", { onclick: "alert('Clicked!')" }, "Click Me")
);
render(vApp, document.body);

3. Implementing Reactivity (State Management)

To make UI reactive, we need a state system that updates the DOM when data changes.

Reactive State System:

function createState(initialState) {
    let state = initialState;
    let listeners = [];
    
    function setState(newState) {
        state = { ...state, ...newState };
        listeners.forEach(listener => listener(state));
    }
    
    function subscribe(listener) {
        listeners.push(listener);
    }
    
    return { setState, subscribe, getState: () => state };
}

Example: Updating UI with State Changes

const state = createState({ count: 0 });

function renderCounter() {
    document.body.innerHTML = '';
    render(createElement("button", {
        onclick: () => state.setState({ count: state.getState().count + 1 })
    }, `Count: ${state.getState().count}`), document.body);
}

state.subscribe(renderCounter);
renderCounter();
  • Clicking the button updates count and re-renders UI.

  • State change triggers reactivity, similar to Vue’s reactive() or React’s useState().

4. Understanding How Real Frameworks Work

Feature

React

Vue

Angular

Virtual DOM

(Direct DOM)

Component-Based

Reactivity

Hooks (useState)

Proxy-based (reactive())

Service-based (RxJS)

State Management

Context API, Redux

Vuex, Pinia

NgRx, Services

5. Event Handling in a Framework

Handling events efficiently is a key feature of frameworks.

Custom Event System Implementation

function createEventBus() {
    const events = {};
    return {
        on(event, callback) {
            (events[event] ||= []).push(callback);
        },
        emit(event, data) {
            (events[event] || []).forEach(callback => callback(data));
        }
    };
}

Example Usage:

const eventBus = createEventBus();
eventBus.on("message", data => console.log("Received:", data));
eventBus.emit("message", "Hello Event Bus!");

6. Optimizing the Rendering Process

To improve performance, real frameworks diff the virtual DOM before applying changes.

Basic Diffing Algorithm:

function diffAndPatch(oldVdom, newVdom, parent) {
    if (!oldVdom) {
        render(newVdom, parent);
    } else if (!newVdom) {
        parent.removeChild(parent.firstChild);
    } else if (oldVdom.type !== newVdom.type) {
        parent.replaceChild(document.createElement(newVdom.type), parent.firstChild);
    } else {
        oldVdom.children.forEach((child, index) => {
            diffAndPatch(child, newVdom.children[index], parent.firstChild);
        });
    }
}

You are reading Part 38 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 6]

  • Views 34
  • Created
  • Last Reply

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

Important Information

Terms of Use Privacy Policy Guidelines We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.