Why State in React is more useful than you think!

Why State in React is more useful than you think!

The React Way

If you have just begun to use React then chances are you might have come across “State”, this concept is easy to grasp but requires a different brain thinking when designing one.

When I was transiting from one basic web technologies ( HTML, CSS, PHP, Vanilla JS ) I’d never used anything called “State” of an element or an object. React is different, it’s more of thinking from the perspective of a component than a perspective of a developer (At least, I think so).

State defines the behavior of an object. React does not allow us to modify this.props on our components, and sometimes a component needs to able to update its own state.

Below will be some examples for your brain to get a grasp on the concept so that eventually your brain can think of this effortlessly.

Let us start with a very simple one, you would have used it before. It’s a search icon when clicked toggles the search input box.

Fig.1. Toggling Search Bar

Fig.2. Pseudo Code for toggling search bar

Example 2: Dice App

The next one is a simple dice app in which the dice component has multiple states that is lose, win and draw. A random function is used to calculate a number between 1 to 6 and the corresponding dice image is been displayed. If the userChoice == gameChoice : DRAW STATE

userChoice > gameChoice : WIN STATE

userChoice < gameChoice : LOSE STATE

Fig.3. Dice app

Fig.4. Pseudo Code for Dice App State

Example 3: Counter

It ‘s a very small app but useful to make when starting out, since it covers basic functionalities like updating, deleting, or resting an element. This GitHub project has the entire code for it.

Fig.5. Counter App

Fig.6. Pseudo Code for counter app

We can use some special methods on the component class to run some code when a component mounts and unmounts in order to free up resources taken by the components when they are destroyed. The two methods are:

  1. componentDidMount()
  2. componentWillUnmount()

These two methods are called “lifecycle methods”.

  1. componentDidMount(): This method runs after the component output has been rendered to the DOM.
  2. componentWillUnmount(): This method unmounts the component and thus free up resources used by these components.

A classic example to showcase these two lifecycle methods will be a clock/timer. If you want the entire code, check out this code pen from Dan Abramov.

Fig.7. Clock App

Fig.8. Pseudo Code for Clock App

In conclusion, the state of the components should be defined from the perspective of a component.

Thank you for reading :)

Did you find this article valuable?

Support Rahul's Tech Blog by becoming a sponsor. Any amount is appreciated!