How UseState Can Keep Data Organized in a Multi-component Application
Published: 2023-07-19 13:30:37

When you first start learning to program in React, UseState is one of the first aspects that you will be exposed to that is different than vanilla Javascript. UseState can be confusing but once understood is a powerful way to manage data and visual elements across multiple files. Learning how to effectively employ useState will keep your app working nice and cleanly making your development process less prone to mistakes and headaches.

When you build a react app eventually you will want to use several files to manage the various functions of your application but this creates a problem. When working with multiple files, eventually you will need to reassign variables holding your data. This can start to add complexity and more code which requires more time and effort to finishing your project. 

Not only that your will need to rerender the screen to the updated information which means reusing or rewriting functions. Using States can simplify this process and can lessen the amount of code that you need to write for your program.

For example, a game application with money, items or hit points might need to be rerendered when changed. Simply changing the state will keep your program lean and mean. The examples below show how useState can save time and effort when rendering your application.

This example uses a counter that could be for game elements that are updated every time the button is clicked. 

```
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

```

The count state can be changed when other events happen by just changing the state like so:

```
setCount(10)
```

If we look at Javascript to accomplish the same thing it gets much more intense and is more work. 

```
<div id="counter"></div>

<script>
  function useState(initialValue) {
    let value = initialValue;
    const setValue = (newValue) => {
      value = newValue;
      render();
    };
    return [value, setValue];
  }

  function createElement(tagName, props, ...children) {
    const element = document.createElement(tagName);
    for (let prop in props) {
      if (prop.startsWith('on') && typeof props[prop] === 'function') {
        const eventName = prop.substring(2).toLowerCase();
        element.addEventListener(eventName, props[prop]);
      } else {
        element[prop] = props[prop];
      }
    }
    children.forEach((child) => {
      if (typeof child === 'string') {
        element.appendChild(document.createTextNode(child));
      } else {
        element.appendChild(child);
      }
    });
    return element;
  }

  function Counter() {
    const [count, setCount] = useState(0);

    const increment = () => {
      setCount(count + 1);
    };

    const render = () => {
      const counterElement = document.getElementById('counter');
      const element = createElement('div', null,
        createElement('p', null, `Count: ${count}`),
        createElement('button', { onclick: increment }, 'Increment')
      );
      counterElement.innerHTML = '';
      counterElement.appendChild(element);
    };

    render();
  }

  Counter();
</script>

```

In the above example we are creating elements and you might not want to do that in your application, but that is the beauty of React. Because each React component is rerendered when a state is changed we can make our application interactive in a way that is just too time consuming with vanilla Javascript.

This example also is just to create elements and assign values, if our button is clicked we still have to write code for that. UseState we just need to reassign our variable like so...

```
setCount(10)
```

... and React will rerender our on screen changes. The difference is striking and is just one change. Imagine a program with 20 variables like this that all needed to be changed on user events. React does so much of the heavy lifting its no wonder many apps like Facebook, Netflix and Dropbox.

Using states is one of the best aspects when coding in React because rerendering just means changing states. In Javascript it means removing and creating elements on user interaction which makes it far more time consuming and far more prone to errors the more complicated our code gets.

React can be challenging to understand when first learning but once you do the rewards far outweigh the challenge of learning it.