DEV Community

Cover image for The Analogy of State Management in React
Adeyemi Simeon
Adeyemi Simeon

Posted on • Updated on

The Analogy of State Management in React

A react web application is made of several parts, called Components. Components are smaller blocks of a website, for example, the Navbar, Form, Button, Tags, etc. These components some times contain data (a piece of information) or not.

If a component contains data, it is called a Stateful component else it is called a Stateless component.

class StatefulComponent extends React.Component {
  state = {
    text: "I have some internal data"
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>{this.state.text}.</h2>
      </div>
    );
  }
}


function StatelessComponent(props) {
  return (
    <div>
      <h1>Hello, world!</h1>
      <h2>I don't have any data internally</h2>
    </div>
  );
}

Components in a web app are arranged in such a way that data flow from the topmost level to the least level. This is to enable same piece of data to be shared among multiple components.
Imagine a wine glass tower. When the wine is poured to the topmost glass if filled up, it runs over to the next level glass and then to the next level and it goes on till it reaches the bottom of the glass.

wine glass tower image here

Analogy of state and props in React

When a component has its data local or encapsulated, that data is called state. That is, if a glass of wine has its own wine, we can call that wine, state. This also implies that the component can change its "wine" (or rather data).
If the wine is coming from the previous level above, meaning the data is not local or encapsulated, we call it Props. The component cannot do anything about the "wine" flowing into it.

Why we need state management?

Imagine you want wine in a glass six levels deep, you have to start pouring the wine from level one and keep pouring till overflows through level one, two, three, till six. You will find this exhausting in a matter of time. Hence, there ought to be a better way to get your wine. By the way, the above process is called “Prop drilling”.

wine tower image

A more astute approach is to call a "bartender" whenever we need wine and he fills the exact glass you need the wine in. The job of this bartender is similar to the job of state management in React. That is, to provide the various components with the piece of data they need per time, without passing the data from components to components.

3 Popular ways to manage your state

There are three major ways (but not limited to these) you can manage your state in React which

  • Redux (most popular way)
  • Mobx (redux alternative)
  • Context API (a good alternative, recently popular)

Thanks for reading this far, your feedback and questions are welcome.

Oldest comments (0)