React 'useState' hook and its use cases

React 'useState' hook and its use cases

React has introduced the 'useState' hook in V 16.8 onwards as a provision to declare the state inside a functional component rather than the class components as well.

In the Class component, we could declare a state and the data types have to be declared inside the properties of an object only. But using the usestate hook, we can declare the data in the following formats:

  1. Number

  2. String

  3. Object

  4. Array

  5. Boolean

Basically, useState returns an array of two elements which have the 'variable name' and the 'function' which manipulates the variable.

  const [count, setCount] = useState(0); //For Numbers

  const [welcomeNote, setWelcomeNote] = useState("Hello Guest!"); //String

  const [display, setDisplay] = useState(true); //boolean

  const [fullName, setfullName] = useState({
    firstName: "Jon",
    lastName: "Snow!"
  });

  const [employeeIds, setEmployeeIds] = useState([10, 20, 30]);//array

The manipulation of the state can be done in two ways.

  1. Assigning the state to a new state value

  2. Manipulating the state with the previous value of the state

//This is directly assigning the state to a new value or new state  
<button onClick={() => { setCount(count + 1) }}>Increment</button>

//Also, we can manipulate with the previous value of the state and produce a new state 

const resetCount = () => {
        setCount(prevCount => {
            return prevCount + 1
        },)
    }

const incrementByFive = () => {
        for (let i = 0; i < 5; i++) {
            setCount(prevCount => prevCount + 1)
        }
    }

While dealing with the Objects and Arrays, we have to consider the old value of the state with the rest operator and can return the updated value to that Object or array.

//Rest Operator can be used for combining two arrays and objects 
var array1 = [10, 20, 30, 40, 50];
    var array2 = [60, 70, 80, 90, 100];
    var array3 = [...array1, ...array2];
   console.log(array3); 
//OutPut 
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

//For changing the fullname state
const changeName = () => {
    setfullName({
      firstName: "Aegon",
      lastName: "Targaryen"
    });
  };

const updateEmployee = (emp) => {
        console.log(emp);
        setEmployeeIds([...employeeIds, emp]);
    }

In the following snippet, there's a component where all the data types for a state are declared.

There's one drawback of the useState hook, unlike the setState in class component, we can't track the value of the updated state in the callback function as a second parameter to the setState function.

setState(prevCount => {
         return prevCount + 1
        }, ()=>{
            console.log(count)
        }
    )

We have to use another hook which is useEffect to trace the state change.

useEffect(() => {
    console.log("called", count);
  }, [count]);

These are the ways how we can make the use of useState hook to declare the state. Hope you liked it, happy coding. Thank you!

Did you find this article valuable?

Support Ajinkya Chanshetty's Blog by becoming a sponsor. Any amount is appreciated!