Logo

dev-resources.site

for different kinds of informations.

State Management with Vanilla JavaScript

Published at
3/10/2021
Categories
vanilla
javascript
redux
context
Author
christosmaris
Categories
4 categories in total
vanilla
open
javascript
open
redux
open
context
open
Author
13 person written this
christosmaris
open
State Management with Vanilla JavaScript

TL;DR

| Check this Codepen out.


Intro

After reading this article on how to create a state management library using Vanilla JS I was intrigued to do something similar but in a more developer-friendly manner.

We basically want something that makes it easy for us to update the state, without having to invoke functions like setState and without having to trigger a UI refresh manually. This means that we should be able to do something like App.state.count++; and that should be enough for the UI to be refreshed.

For this reason, we will be using JS Proxies.
Basically, a Proxy is like a middleman between you (the developer) and the object you are trying to read or edit. It allows us to intercept and redefine fundamental operations for that object, which is a fancy way of saying that we know every time someone tries to edit or read a property from that object.


Code

Now in order for us to create a basic state management system, we need to create the following things:

  1. The App returns the UI that encapsulates the app state.
  2. The App State encapsulates
    • the actual state object
    • and the middleware proxy.

The App

| All we want from the app is to return a UI that basically displays the state.

const App = function _App() {
  return `
    <h1>Vanilla State Management</h1>
    <button onClick='App.state.count++;'>You pressed me ${App.state.count} ${App.state.count === 1 ? 'time' : 'times'}!</button>
  `;
};
Enter fullscreen mode Exit fullscreen mode

The App State

| The State Object in combination with the Middleware Proxy that updates the UI every time something in the state object is changed.

const handler = {
  set: function(obj, prop, value) {
    obj[prop] = value;
    document.getElementById('app').innerHTML = App();
  },
};

App.state = new Proxy({ count: 0 }, handler);
Enter fullscreen mode Exit fullscreen mode

Wrap Up

| This is what the complete thing looks like.

<body>
  <div id="app">loading...</div>
  <script>
    const App = function _App() {
      return `
        <h1>Vanilla State Management</h1>
        <button onClick='App.state.count++;'>You pressed me ${App.state.count} ${App.state.count === 1 ? 'time' : 'times'}!</button>
      `;
    };

    const handler = {
      set: function(obj, prop, value) {
        obj[prop] = value;
        document.getElementById('app').innerHTML = App();
      },
    };

    App.state = new Proxy({ count: 0 }, handler);

    // Initial Loading of the App
    document.getElementById('app').innerHTML = App();
  </script>
</body>
Enter fullscreen mode Exit fullscreen mode
vanilla Article's
30 articles in total
Favicon
🎨🛠️ 𝗩𝗮𝗻𝗶𝗹𝗹𝗮 𝗙𝗿𝗮𝗺𝗲𝘄𝗼𝗿𝗸 𝘁𝗼 𝗘𝗺𝗽𝗼𝘄𝗲𝗿 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 🚀🌐
Favicon
Mastering Vanilla JavaScript and Libraries: The Road to Dynamic DOM Rendering
Favicon
🌟 Vanilla Update: New Components and Enhanced Features! 🌟
Favicon
🌐 Unlock Development with Vanilla: The Non-Framework Powerhouse 🌐
Favicon
🚀 Vanilla & CSSer Major Update! 🚀
Favicon
How to upload files to a server in NodeJS with Formidable
Favicon
🚀 Vanilla Update: A New Development Methodology! 🚀
Favicon
Secure Text Encryption and Decryption with Vanilla JavaScript
Favicon
🚀 Vanilla Framework Update: Meet CSSer! 🚀
Favicon
🌟 Vanilla & CSSer Accessibility Update! 🌟
Favicon
Storing and retrieving JavaScript objects in localStorage
Favicon
New lightbox package here!
Favicon
Data-driven UIs
Favicon
A11y: Vanilla javascript aria-live announcer
Favicon
Keyboard input in Node.js
Favicon
Javascript Made Simple!
Favicon
Array methods and when to use them, forEach, map, reduce
Favicon
Which should you use? Array.from vs. Spread Operator
Favicon
Tiny Vanilla.js Projects
Favicon
Maneras de clonar un objecto en javascript
Favicon
Vanilla JavaScript data fetch
Favicon
Vanilla(ts) configuration with Webpack. a little bit different.
Favicon
My first Chrome Extension
Favicon
Speedy Typer Game
Favicon
What is CSS @scope and why should I care?
Favicon
Path aliases with Vanilla Node JS
Favicon
Montar SPA de cero con Vanilla y Jest
Favicon
Web Apps from scratch: Forms
Favicon
Sending asynchronous POST requests with pure JS: ditching jQuery's ajax
Favicon
State Management with Vanilla JavaScript

Featured ones: