DEV Community

Cover image for What are states in React?
Rahul
Rahul

Posted on

What are states in React?

In this tutorial, we will learn what are STATES and how to use it with react hooks.


What are States?

The state is the object where you store information about the components. Whenever the state changes, react re-renders the component.

You can understand this as the "memory" of the component.

Understanding States in-depth

States is one of the most difficult concepts to learn as a beginner. However, it is the core fundamentals of React. Let's try to understand this with a simple example of the counter app.

c.png
The + and - are stateless components. They remain the same in the entire application.
The counter(the number that is displayed) is a stateful component. It means that it changes its values (whenever a user clicks the increment/decrement button). So in this case state is an object to store the value of this counter.

State of the component exists throughout the app. So every stateful component must have an initial state. For class-based components, we do this in the constructor function. But the modern way is to create function components and use hooks to access the states.

We will learn about hooks in details in the next post. However here we will see how we can set the state using useState hook. Consider the following code.

import React from 'react';

let Cool = () => {
 return (
   <p>This is reusable component</p>
  ); 
}

export default Cool; 
Enter fullscreen mode Exit fullscreen mode

Creating a Stateful Component

The Cool component above is currently a stateless component as it does nothing but displays a message. Lets turn into a stateful component using the useState hook.

Let's consider this:

import React, { useState } from 'react'; 

let Cool = () => {
  const [msg, setMesg] = useState("This is the initial message."); 
  return (
    <div>
       <p>{ msg }</p>
       <button onClick = {() => setMsg("This is the changed message")} > Change State </button>
     </div>
   ); 
}

export default Cool
Enter fullscreen mode Exit fullscreen mode

*Now let's understand the above code line by line. *

This is a very simple component which changes its state when we click the button. We start by importing the useState hook from react. Then we declare two variables msg and setMsg and set it equal to the useState hook.

The*useState* hook returns two values - first is the current state and second is the function that updates it. Since we are using the array destructuring syntax, the first value (current state) is assigned to the first variable (msg) and the second value is a function assigned to the second variable (setMsg).

The useState hook takes the initial state as the argument. So the vaue of msg* variable is set to the argument inside useState hook (that is "This is the initial message").

The setMsg function takes the new state as an argument and is attached to the onClick event of the button. So whenever the button is pressed setMsg is called and the value of msg is updated.

Let's see this again.

import React, { useState } from 'react'; 

let Component = () => {

 const [state, setState] = useState( initialState ); 

 return (
    //Some JSX
  ); 
}

export default Cool; 

////////////////////////////////////////////////////////
// Component => Our function based component
// state => Variable to store the current state
// setState => Variable (function) to update the state
// initialState => The initial state of the state variable 
Enter fullscreen mode Exit fullscreen mode

Rules for using State by useState hook

  • State should always be updated using the setState function (or whatever is the name of your second variable while declaring the state)
  • You can use multiple state hooks (or any other hooks) in a single component
  • Hooks should only be called at the top level. It cannot be called inside loops, conditionals or nested function.
  • Hooks can only be called from Function Components and not for regular JavaScript functions or Class-based Components.

Important Notes...

  • Don't get intimidated by the word "hooks". Hooks are nothing but functions which "hooks into" some react features which were earlier unavailable for the Function Components. There are other hooks as well which we will see in detail in the next post maybe.
  • If you are already writing react code using class-based components, you can start learning the transition as it is an easier, more intuitive and modern way of writing react code. However, classes are not going to be removed from react as of now.
  • If you have just started learning to react, make sure that you learn to write function based components properly and manage states using the useState hook.

💻Thanks For Reading | Happy Coding ⚡

Top comments (1)

Collapse
 
olanetsoft profile image
Idris Olubisiđź’ˇ

Thanks for sharing