The State within JavaScript

What is State?

Establishing, updating, and otherwise manipulating the “state” of a system is a core concept of computer science. Broadly speaking, state can be defined as the stored value for inputs of a given application. The sum total of all data stored within the an application’s variables and constants can be loosely thought of as the state of an application. Notably, the data stored in the state of variables are susceptible to alteration through out the course of the applications run time.

JavaScript’s State

A common use case for state management within JavaScript is its ability to enable responsive user interfaces(UI) on website by manipulating the DOM. An example often used to illustrate how state can used to implement dynamic solutions to UI problems is a simple HTML <button> element which, on click, increments an integer counter.

// define a variable to store statelet state = {
count: 0,
};
// set up counter componentconst counterComponent = (count) => 
`<div>
${count}
<button onClick="increaseCounter()">
Increase Counter
</button>
</div>`;
// define a render function to update the DOM treeconst renderComponent = () => {
document.getElementById('app').innerHTML = counterComponent(state.count);
};
// set state directlyconst increaseCounter = () => {
let countPlusOne = state.count + 1;
state.count = countPlusOne;
};
// create event listenerconst button = document.querySelector('button');button.click(() => {
increaseCounter();
renderComponent();
});

Conclusion

JavaScript is surprisingly flexible when it comes to utilizing state, especially for a functional language. With ES6, there are even more elegant solutions for state management by utilizing classes. In the future blog posts I will explore how state works within the React library, and compare it to class based JavaScript. We will also explore the state management tools, such as Redux, which are commonly used within React to management state inside of large web applications.

Resources

  1. A Complete Introduction to State For JavaScript Developers
  2. Build a state management system with vanilla JavaScript
  3. State in JavaScript explained by cooking a simple meal
  4. Stateful Components in Vanilla JS

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store