State Management in React

Aswathy E G
3 min readJul 19, 2021

--

An introduction to state management in functional and class components in React

Image by xegxef from Pixabay

Introduction

One of the main advantages of React is it’s huge ecosystem of libraries to choose from. Hence, for state management in complex applications, developers use React Hooks and libraries like Redux. But how do we manage state in simple, small applications? We’ll analyze the same in this article.

Before we start, if you are completely new to React with TypeScript , please refer to my earlier article on the same.

What are we trying to do?

Here I’ll explain the difference in state management in functional and class components with a simple counter example. The output of both the applications will be same as below. The Current Value field gets updated based on the click events.

What is State in React?

State variables are initialised and managed by the component and change over the lifetime of a specific instance of this component. In both class and functional components, when updating the state, we should not update it directly.

State Management in Class Components

Interface

React.Component takes two types as generics, one for the props and one for the state. Both of these should be declared as an interface. The initial state variable (here ‘count’) is declared in state interface.

Constructor

Constructor functions, is the first function called in a class when it is first instantiated. Binding ‘this’ to the class methods enables us to access props and state for the component with this.props and this.state.

Click Events

Both the click events include setState method. If we try to update state directly then it won’t re-render the component. Hence updation of state is done by setState method .

Following is the complete code example:

State Management in Functional Components

UseState Hook

Functional components are called stateless components. In functional components, we need to use the useState hook to be able to handle state.

The useState has two parameters. First is the initial state variable( here ‘count’). The function useState(0) sets the count value to zero.

Second is a function (here ‘setCount’). Both the click events go to setCount function, which update the state in functional components.

Following is the complete code example:

What is the Difference between Hooks and Class-based State Management?

In class-based state management, there is a single state object. With Hooks, state objects are completely independent of each other, so you can have as many state objects as you want. Hence if you want a new piece of stateful data, all you need to do is call useState with a new default and assign the result to new variables.

That’s all for today. Thanks For Reading !

--

--