Everything you need to know about State in React | Beginners Tutorial

Iqra Jamil
3 min readOct 9, 2022

--

React Js is one of the world’s most popular front-end development frameworks, with over 10 million websites running with it.

Photo by Lautaro Andreani on Unsplash

This post assumes that you know about components in react. React components are broadly classified into functional and class components. Functional Components are faster and much simpler than Class Components. The primary difference between the two is the availability of the State. Now let’s get to the point.

Photo by Juanjo Jaramillo on Unsplash

What is State?

The state represents parts of an application that can change. It generally refers to data or properties that need to be tracking in an application. Each component can have its state. The state is mutable and is local to the component only.

In short, The state is both read & write and is encapsulated.

3 things you should avoid while using State:

Here I will be talking about three things that can save you from hustle and bugs :D

  1. Don’t directly update the state, It will not re-render.
  2. States updates may be asynchronous so you should not rely on their values for calculating the next state.
  3. State updates are merged shallow. Shallow merging only merges things on the first level though (hence the term shallow), which means that we have to be careful when we use setState( ) on state objects with nested structures.

How to Use useState( )?

Importing: To use useState you need to import useState from react as shown below:

import React, { useState } from "react"

Syntax:

const [state, setState] = useState(initialstate)

useState() hook accepts an initial state and returns two values:

  • The current state.
  • A function that updates the state.

See the example below:

Note: The state variable can be initialized to null and set to the specified type later on in your code.

Why use useState( ) instead of variables?

The reason is if you useState it rerenders the view. Variables by themselves only change bits in memory and the state of your app can get out of sync with the view.

Summary

In this tutorial, we learnt about states, and things to avoid while writing code. Moreover, we learnt how to use the useState() hook and why we use useState() instead of variables in React.

For upcoming stories, you should follow my profile Iqra Jamil.

That’s it, guys! Have fun, keep learning & always coding!

--

--