React useState() Hook

Last Updated On Friday 17th Jun 2022

React Hooks are functions used in a function component to hook into React’s state object, lifecycle methods, and other React features without writing a class component.

The React useState Hook allows us to track state in a function component. Whenever you want to create variable, then you have to use useState() hook.

useState Hook

The State Hook (useState) allows a function component hook into React’s state object.

Syntax

	import React, { useState } from "react";

const [ age, setAge ] = useState(19);
	

Returns

useState to return an array because they advocate using array destructuring to access a function component’s state.

  • The current state.
  • A function that updates the state.

You can call useState() multiple times. React recommends splitting state into multiple state variables based on which values tend to change together.

Example : Simple Counter

	function Counter() {
   const [count, setCount] = useState(0);
   const increment = () => setCount(prevCount => prevCount + 1);

   return (
     <div>
       <p>Clicked: {count} times !!!</p>
       <button onClick={increment}>Increment</button>
     </div>
   );
}
	

Example : Array with Names

	function Names() {
 const [names, setNames] = useState(['tsr']);

 const addName = () {
   setNames((prev) => {
     return [...prev, 'CJ'];
   });
};
	
  • ... spread Operator is used to maintain the previous state array
  • Then Adding the new name to the end
  • If we wanted to add the new name to the start we could have [name, ...prev]

Example : Working with Object

	function Person() {
  const [details, setDetails] = useState({
     name: 'CJ',
     email : 'contact@codejagd.com'
  });
    const handleChange = ({ }) => {
      setDetails((prev) => ({
        ...prev,
        'website' : 'codejagd.com'
      }));
};
	
  • We have an object containing multiple details about me.
  • We pass a name: value pair into our setDetails function that also uses …prev to change the state to the previous object with the new value pair appended to the object.