Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is state management in JavaScript

Understanding State Management

Let's start with the term "state". In programming, a state simply refers to the status of a system or an application at a specific moment. For instance, if you are logged in a website, the website is in an "authenticated" state. If you log out, the website is in an "unauthenticated" state.

Now, managing these states efficiently is what we call "state management". It's like a librarian keeping track of all the books in a library.

Why is State Management Important?

Imagine you're building an online shopping website. There are so many different states to manage! Is the user logged in? What items are in their cart? Have they entered their shipping information? And so forth.

If we don't keep track of these states properly, we might end up showing irrelevant information to the user or even worse, lose their shopping cart data! That's why we need state management.

The Basic Way: Using Variables

The most basic way of managing states in JavaScript is by using variables. Here is a simple example:

let isLoggedIn = false;

function logIn() {
  isLoggedIn = true;
}

function logOut() {
  isLoggedIn = false;
}

// When the user logs in
logIn();
console.log(isLoggedIn); // true

// When the user logs out
logOut();
console.log(isLoggedIn); // false

In this example, we're using a variable isLoggedIn to keep track of whether the user is logged in or not.

The Not-so-Basic Way: Using State Management Libraries

When you're building advanced applications, your state can get extremely complex. To manage these complex states, we can use state management libraries like Redux or MobX.

Let's see a simple example of how we can use Redux to manage state:

import { createStore } from 'redux';

// This is our initial state
let initialState = {
  isLoggedIn: false
}

// This is our reducer function. It's responsible for updating the state.
function reducer(state = initialState, action) {
  switch(action.type) {
    case 'LOG_IN':
      return { isLoggedIn: true };
    case 'LOG_OUT':
      return { isLoggedIn: false };
    default:
      return state;
  }
}

// We create a store using the reducer
let store = createStore(reducer);

// When the user logs in
store.dispatch({ type: 'LOG_IN' });
console.log(store.getState().isLoggedIn); // true

// When the user logs out
store.dispatch({ type: 'LOG_OUT' });
console.log(store.getState().isLoggedIn); // false

In this example, Redux helps us to manage our state in a more systematic way. We define an initial state and a reducer function to handle how the state should be updated. We then create a store that stores our state and provides us methods to update and get the state.

Making Things Easier: Using React's useState Hook

If you're building a React application, there's an even easier way to manage state using the useState hook. Here's how you can do it:

import React, { useState } from 'react';

function App() {
  // We use useState to manage the isLoggedIn state
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  function logIn() {
    setIsLoggedIn(true);
  }

  function logOut() {
    setIsLoggedIn(false);
  }

  // We show different content based on the isLoggedIn state
  return (
    <div>
      {isLoggedIn ? (
        <button onClick={logOut}>Log Out</button>
      ) : (
        <button onClick={logIn}>Log In</button>
      )}
    </div>
  );
}

In this example, the useState hook gives us a variable isLoggedIn and a function setIsLoggedIn to update the variable. We can then use these to manage the login state of the user.

Conclusion: State Management is Like a Symphony

In conclusion, state management in JavaScript is like conducting a symphony. Each instrument (or state) plays a crucial role in creating the overall music (or application). The conductor (or state management system) ensures that each instrument is playing correctly at the right time.

Just like how a symphony would be chaotic without a conductor, an application would be chaotic without proper state management. So, as you go on your journey in learning JavaScript, remember to give state management the attention it deserves. It might seem complex at first, but once you get the hang of it, you'll be creating harmonious applications that users will love!