Dead simple State Management in Vanilla JavaScript
It's been years now since you started using Redux, MobX or even plain React Hooks and have no idea how state management works and why it works the way it works? I'll show you the dead simple bottom level of work in state management sans any optimization or other bells and whistles.
We will be building a stupidly simple plain ol' HTML page with script tags in it.
<!DOCTYPE html>
<html>
<head>
<title>State Management in Vanilla JS</title>
</head>
<body>
<div id="app"></div>
<script>
//
</script>
</body>
</html>
Now let's write some JavaScript.
NOTE: TL;DR; is down below โฌ
const App = function _App() {
return `
<h1>Hello Vanilla JS</h1>
<div>Example of state management in Vanilla JS</div>
`;
}
document.getElementById("app").innerHTML = App();
I could have simply declared as
const App = function() { // ...
// or
const App = () => { // ...
But there's reason I didn't, which I'll explain later. Now, let's create some state
App.state = {
count: 0,
increment: () => {
App.state.count++;
}
};
A simple state created as a property on App function. ๐
Wait! You can do that? ๐ฒ
Yes, everything in JavaScript is an object, and technically you can even do that on strings and numbers. That is why methods like "hello world".toUppercase()
and (12).toFixed(2)
would work. But the compiler doesn't allow you to define your own properties on a string or number.
Now that App has been made stateful, we shall integrate the state and add a click event listener at the end of file.
`
<h1>${_App.state.count}</h1>
<button id="button">Increase</button>
`
// ...
document.getElementById("app").innerHTML = App();
// On Click Function
document
.getElementById("button")
.addEventListener("click", App.state.increment);
Note that I'm accessing App inside itself by neither this
nor by App
but by _App
. This is called as "Named function expression"
There are two special things about Named function expression:
- It allows the function to reference itself internally.
- It is not visible outside of the function.
Even if I do something like this below, the code won't break.
const Component = App;
App = null;
document.getElementById("app").innerHTML = Component();
Even when App has been reassigned to Component and then made to be null, the function itself remains intact and it refers itself as _App locally, hence it is not affected. Same as 'this
' in every other OOP programming language (But We all know how this
works in JavaScript)๐
.
Now try running it (simply double click the index.html file). Notice that the on click function isn't working! ๐ It's because the UI is not reflecting the latest state, let's fix that by re-rendering the elements. This can be done by running this code again when the state is updated.
document.getElementById("app").innerHTML = App();
// On Click Function
document
.getElementById("button")
.addEventListener("click", App.state.increment);
Since this code is and will be repeated, we will extract it to a function
const updateTree = () => {
document.getElementById("app").innerHTML = App();
// On Click Function
document
.getElementById("button")
.addEventListener("click", App.state.increment);
}
Now add a setState function
const setState = (callback) => {
callback();
updateTree(); // extracted function
}
and update the increment function as
increment: () => {
// Call our set state function
setState(() => App.state.count++);
}
Now our App works as expected. And that's it! that's the end of Dead simple State Management in Vanilla JavaScript. However just using as it is would be consider as an awful and poor framework, not because of its lack of any bell and whistles worthy feature, but because it is poorly optimised, in fact it has no optimisation, but you already know this when I said "โฆsans any optimization or other bells and whistles" in the beginning of this article.
Things to do,
- Should not render the whole application to reflect a simple change.
- As soon as we update to reflect the state, all the event listeners attached to DOM should not be lost and we shouldn't add new event listeners in its place.
- The DOM elements that were unaffected and unchanged by state should not be forced to change. Changes should be as small as possible
So we shall few optimisations to our App like how React and similar library / framework does in the next upcoming article.
TL;DR;
Here is the full HTML file we have coded so far.
<!DOCTYPE html>
<html>
<head>
<title>State Management in Vanilla JS</title>
</head>
<body>
<div id="app"></div>
<script>
const App = function _App() {
return `
<h1>Hello Vanilla JS!</h1>
<div>
Example of state management in Vanilla JS
</div>
<br />
<h1>${_App.state.count}</h1>
<button id="button">Increase</button>
`;
};
App.state = {
count: 0,
increment: () => {
setState(() => App.state.count++);
}
};
const setState = (callback) => {
callback();
updateTree(); // extracted function
}
const updateTree = () => {
document.getElementById("app").innerHTML = App();
document
.getElementById("button")
.addEventListener("click", App.state.increment);
};
updateTree();
</script>
</body>
</html>
Updates:
- (13 Mar 2021) Added
setState
function, fixed few typos, added link for named function expression.
Top comments (33)
Here is an optimised version :-)
You can test it here : SSMOPT
And if you want to get a little further
You can test it here IntroSamPattern
Thank you for your post.
Here is a variation :
You can test it here : SSM
Regards
This one is great. Makes better use of functional programming.
I don't want to come off sounding like an asshole, but is this satire?
It feels like someone whose never learnt JavaScript, and just copied react examples suddenly learnt how the language works... Unless I'm missing something fundamental.
Please, be comprehensive...
Are you sure you didn't want to come off sounding that way? I'm pretty sure you did.
This is a nice explaination and it helps you understand the state management concept behind the scene. Good work ๐
So happy to see some framework-agnostic content. This is a great read and shows sometimes we can get by just fine with the standard web technologies.
I was really wondering why you had _App and App but your justification is brillaint.
Hi Vijay Pushkin,
I know this tutorial is not about the best code but I couldn't help myself from refactoring your code ;).
Hello,
here is the code of utml (877lines)
uhtml.js
You can test it here : uhtmltest
Optimized in a sense, it uses VDom Diff to update the page.
Regards
Great insight
Really into this, thank you for sharing! The cognitive burden of many frameworks is too high for what one gets in return.
I've found this routine to be helpful for rendering the state of arbitrary objects to the DOM. Additionally, when using standard HTML
template
tags, I've used another routine to populate slots (template parameters) and render the template at runtime.When's the next article which I hope will be web components leverage native shadow Dom to handle updates when state changes :)
Nice article by the way. Good starting point.
Nice Insight on state management, waiting for the upcoming article.
Is your lastname really Pushkin? Like Alexander Sergeyevich Pushkin?
The place where I'm from, we don't have family names. So, yes both are my names!
Understood, cool. Pushkin is perhaps the greatest person in Russian literature. I am from Kazakhstan and we happen to speak and learn russian language at school. Anyways you have a great name!
Vanilla javascript? I've never heard of that library.
Wow! ๐ฎ๐๐ฅฐ What an amazing tutorial! Now I can start writing my own front-end web framework. ๐๐๐๐ Just kidding, I won't! But I've always wanted to know how to. Thank you for the article! ๐๐
hey what does it mean when you add redraw in curly braces i.e return {redraw}. Please someone explain
Some comments may only be visible to logged-in visitors. Sign in to view all comments.