How to Build a Minimalistic State Management System from Scratch

Learn how to create a simple and minimalistic state management system in JavaScript from scratch. This tutorial is perfect for beginners who want to understand the fundamentals of state management without any external libraries.

State management is an essential concept in modern web development. It helps you keep track of your application's data and how it changes over time. Popular libraries like Redux or MobX manage state for you, but understanding how they work under the hood is crucial for becoming a better developer. In this tutorial, we'll build a minimalistic state management system from scratch using plain JavaScript.

Our system will have three main features: 1. A state object to store data. 2. A way to update the state. 3. A subscription system to notify when state changes.

Let's get started!

javascript
function createStore(initialState) {
  let state = initialState;
  const listeners = [];

  // Get the current state
  function getState() {
    return state;
  }

  // Update the state and notify listeners
  function setState(update) {
    state = { ...state, ...update };
    listeners.forEach((listener) => listener());
  }

  // Subscribe to state changes
  function subscribe(listener) {
    listeners.push(listener);
    // Return an unsubscribe function
    return () => {
      const index = listeners.indexOf(listener);
      if (index > -1) {
        listeners.splice(index, 1);
      }
    };
  }

  return { getState, setState, subscribe };
}

Here's a breakdown of this code: - `createStore` takes an initial state object. - `getState` returns the current state. - `setState` merges the new updates into the existing state and calls all subscribed listeners. - `subscribe` lets other parts of your app listen for changes in the state and returns an unsubscribe function to stop listening.

Let's see how to use this store:

javascript
// Create a store with an initial state
const store = createStore({ count: 0 });

// Create a listener function to respond to state changes
function render() {
  console.log("Count:", store.getState().count);
}

// Subscribe the listener
const unsubscribe = store.subscribe(render);

// Initial render
render();

// Update the state - this will trigger the listener
store.setState({ count: store.getState().count + 1 }); // Count: 1
store.setState({ count: store.getState().count + 1 }); // Count: 2

// Stop listening to changes
unsubscribe();

// This update will not trigger the listener
store.setState({ count: store.getState().count + 1 });

This simple system shows the core concepts of state management: you create a store, read from it, update it, and react when it changes. You can extend this system by adding features like middleware, action creators, or more complex state updates, but this minimalistic setup is a great starting point.

Congratulations! You’ve just built your own minimalistic state management system.