useState() Hook in React: A Comprehensive Guide
Tags: react, webdev, beginners, tutorial
Published: 2023-07-12 04:00:00

> _This blog is originally published on my Blog website, where you can find the full version with detailed insights and examples. Click the link below to read the complete article and explore more tech-related content!_
> 👉 [Click Here](https://devwebbytes.blogspot.com/2023/08/reactjs-state-management-made-easy-with-usestate-hook-step-by-step-guide.html)

## Introduction:
One of the most used react hook is `useState()`, it lets you add a state variable to your function-based component. In this article, we'll dive deep into the `useState()` hook, its syntax, and usage examples.

### Explanation of useState() Hook:
The useState() hook takes an initial value `(String, Number, Array, Object, etc)` as its argument and returns a pair of values: the current state and a function to update the state. This powerful hook enables functional components to have state management capabilities similar to class components.

**Examples**
```javascript
const [state, setState] = useState(initialState); 	// Good
const [state, setState] = useState().			// Bad
```

In the above example JavaScript `array destructuring` is used. It means that we’re making two new variables state and setState, The state variable holds the current value of the state, while setState is a function used to update the state.

To elaborate further, consider the equivalent code without array destructuring:


```javascript
 var stateVariable = useState('banana'); // Returns a pair
  var state = stateVariable[0]; // First item in a pair
  var setState = stateVariable[1]; // Second item in a pair
```

> _Explanation_: When we declare a state variable with useState, it returns a pair — an array with two items. The first item is the current value, and the second is a function that lets us update it. Using [0] and [1] to access them is a bit confusing because they have a specific meanings. This is why we use array destructuring instead.


### Function version of initialValue
When you have very slow and complex computation as an initialValue in state then it will take much time. So to solve this issue you can use the function version instead.

```javascript
import React, { useState } from "react";

export default function ComplexState() {
  let [fibonacci, setFibonacci] = useState((number=7) => {
    console.log("this will call once");
    return FibonacciSeries(number);
  });
  function FibonacciSeries(number) {
    if (number < 2) return number;
    return FibonacciSeries(number - 1) + FibonacciSeries(number - 2);
  }

  return (
    <div>
      <h1>Complex State</h1>
      <p>
        Fibonacci number of 7: {fibonacci}
      </p>
    </div>
  );
}
```
##### Output of above code:
![function inditialValuePractice](https://www.linkpicture.com/q/Capture_138.jpg)


### Objects State:
In some cases, it is important to use object states as they can hold the collection of the same data.

```
const [style, setStyle] = useState({  color: 'red,  fontSize: 20 })
```

While using object states, you have to keep one thing in mind when you try to change current state value using `setState` function you have to  use the spread operator (`...`) to preserve the previous state otherwise you will lose the previous state.

**Example:**
```javascript
import React, { useState } from "react";
 
export default function ObjectState() {
 const [style, setStyle] = useState({
   color: "red",
   fontSize: 50
 });
 function changeStyle() {
   setStyle((prevState) => {
     return {...prevState, fontSize: prevState.fontSize + 2 };
   });
 }
 return (
   <div>
     <h1>Object State</h1>
     <p style={style}>This is paragraph...</p>
     <button onClick={changeStyle}>Font++</button>
   </div>
 );
}
```
 

##### Output of above code:
![Good Practice](https://i.postimg.cc/QxJr3KJL/Object-State-Good.gif)


##### And the output of the above code without using the spread operator is a style return statement (Bad Practice)
![Good Practice](https://i.postimg.cc/vHsdkt9L/Object-State-Bad.gif)


### Conclusion
In this article, we explored the useState() hook in React and learned how to utilize it effectively. We covered the syntax, usage examples, and best practices. By leveraging the useState() hook, you can handle state management efficiently in your function-based components. If you have any additional insights or questions, feel free to leave a comment. Let's continue exploring new concepts and inspiring each other in the world of JavaScript development.
<hr/>
Connect with me on <a href="https://twitter.com/abidullah_786">Twitter</a>, <a href="https://www.linkedin.com/in/abidullah786/">Linkedin</a> and <a href="https://github.com/abidullah786">GitHub</a>! to stay updated and join the discussion!

<a href="https://www.buymeacoffee.com/abidullah786"><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--n7XsGLsY--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy-me-a-coffee" loading="lazy" width="545" height="153"></a>