DEV Community

Cover image for useState() Hook in React: A Comprehensive Guide
ABIDULLAH786
ABIDULLAH786

Posted on • Updated on • Originally published at devwebbytes.blogspot.com

useState() Hook in React: A Comprehensive Guide

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

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

const [state, setState] = useState(initialState);   // Good
const [state, setState] = useState().           // Bad
Enter fullscreen mode Exit fullscreen mode

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:

 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
Enter fullscreen mode Exit fullscreen mode

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.

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>
  );
}
Enter fullscreen mode Exit fullscreen mode
Output of above code:

function inditialValuePractice

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 })
Enter fullscreen mode Exit fullscreen mode

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:

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>
 );
}
Enter fullscreen mode Exit fullscreen mode
Output of above code:

Good Practice

And the output of the above code without using the spread operator is a style return statement (Bad Practice)

Good Practice

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.


Connect with me on Twitter, Linkedin and GitHub! to stay updated and join the discussion!

Buy-me-a-coffee

Top comments (0)