DEV Community

Cover image for React useState hook
Vansh Sharma
Vansh Sharma

Posted on

React useState hook

Before we get into the core of the article, let's go over some key details around React hooks.

What are Hooks?

Hooks were introduced in the React version 16.8. Hooks are the functions that let the user have access to the state and lifecycle method in the function component. Before the hooks were introduced in React, the class component was the only option to access the state and lifecycle methods. Even though class components are no longer required, they can still be found in some legacy code.

There are no plans to remove classes from React β€” we all need to keep shipping products and can’t afford rewrites. We recommend trying Hooks in new code. React doc

Rules for using hooks

  • Hooks can only be used with function components.
  • Hooks can not be conditional like inside the if...else, switch statements.
  • Hooks must only be called at the top level of a component.

React useState Hook

useState hook allows us to track the information of the component between the rendering of the component such information is called the state of the component. State is like the value of the variable declared within the function.

How to use useState

  • Import useState hook

As useState hook is the named export in the React library we can easily import it by destructuring from the React.

import {useState} from "react"

Enter fullscreen mode Exit fullscreen mode
  • How to initialize useState hook

useState hook is initialized on the top of the component by calling in our function component.

Here again, we are destructuring the returning value.

const Counter = () => {

const [count , setCount ] = useState(0)

}

Enter fullscreen mode Exit fullscreen mode

It returns the two values :

  1. "count" is the current state.
  2. "setCount" is the function that is used to update our state.

Common naming convention for the useState hook is:

[ variable , setVariable ] = useState()

Here "variable" can be anything.

Finally, we give the initial state to the hook, which can be anything from object, string, number, array, boolean, or any combination of these. In our case, it is the number.

Initial state = useState(0)

  • How to read the state

Our first returning value will be the value of the state. We can use it anywhere in our component to read the state.

const Counter = () => {

const [count , setCount ] = useState(0)

return (

<h1> Current value is  {count} </h1>

)}

Enter fullscreen mode Exit fullscreen mode
  • How to update the state

We can only update the value of the state using the function returned by the useState hook in this case setCount.

Note: Never update the state directly. Example: count= 25 .

function increaseCount(){

setCount( prevValue => prevValue+1 )

}

Enter fullscreen mode Exit fullscreen mode

Combining the above all code snippets, we get the following codesandbox. Check the App.js file of the following codesandbox.

Update the Objects in the State

In the above section we discussed how to update the numbers in the state but as explained earlier that useState can take object, string, number, array, boolean, or any combination of these as the state. So now in the following points, we will learn How to update the Objects in the state?
When the component's state is updated, the entire state of the component is fully overwritten. However, while using objects in the state, we simply want to update the object's specific property and leave the rest of the properties unchanged.

Let's look at how the state update entirely replaces the prior state without using the previous values from the state.
Here in the function withoutPrevious we update the lastName property to "Bhardwaj".

 function User() {

  // Update without prev values

  const [user, setUser] = useState({
    firstName: "Vansh",
    lastName: "Sharma",
    city: "Delhi"
  });

//  Function to update without prev value
  const withoutPrevious = () => {
    setUser((prev) => {
      return { lastName: "Bhardwaj" };
    });
  };

return (
    <div className="App">
      <h3>
        I am {user.firstName} {user.lastName} from {user.city}.
      </h3>

      <button onClick={withoutPrevious}>
        Update last name without previous values.
      </button>

}

// Original  I am Vansh Sharma from Delhi.

// Output  I am Bhardwaj from.

Enter fullscreen mode Exit fullscreen mode

Now let us look at how to update only the specific property of the object and retaining the actual value of all other properties.
Unlike in the above function here to update the lastName in the function withPrevious we have used the spread operator to spread the previous value in the new state and overwriting only the lastName property.

function User() {

  //  Update with prev values
  const [user1, setUser1] = useState({
    firstName: "Vansh",
    lastName: "Sharma",
    city: "Delhi"
  });

   // Function to update with prev values
  const withPrevious = () => {
    setUser1((prev) => {
      return { ...prev, lastName: "Bhardwaj" };
    });
  };

  return (
    <div className="App">

        I am {user1.firstName} {user1.lastName} from {user1.city}.
      </h3>

      <button onClick={withPrevious}>
        Update last name with previous values.
      </button>
    </div>
  );
}

// Original  I am Vansh Sharma from Delhi.

// Output  I am Vansh Bhardwaj from Delhi.

Enter fullscreen mode Exit fullscreen mode

Check out the codesandbox of the above code here. Do check out the App.js file in the following codesandbox.

That's all for this blog.Β  Continue reading this React hook series to learn more about React hooks. In the next blog, we'll look at the 'useEffect' hook, which can be used to handle side effect functions in React.
Feel free to leave your valuable feedback in the comments below.

To learn more about React, JavaScript, and Web development, follow me on Twitter.

Reference: W3Schools

Top comments (0)