useState Simplified

useState Simplified

Summary:

  • It lets you add a state to a functional component.

  • in classes, a state is always an object.

  • with the state hook, the states don't only have to be an object.

  • The useState hook returns an array with 2 elements.

  • The first element is the current value of the state, and the second element is a state setter function.

Syntax:

const [name, setName] = useState()

a simple example of using a state where we are increasing and decreasing the count

  • when you have to update the state based on the prev state value then always pass in the function inside the state setter which in this case in setCount.

function UsingStateOne() {
  const initialCount = 0
  const [count, setCount] = useState(initialCount)
  return (
    <div>
      Count: {count}
      <button onClick={() => setCount(initialCount)}>Reset</button>
      <button onClick={() => setCount((prevCount) => prevCount + 1)}>
        Increment
      </button>
      <button onClick={() => setCount((prevCount) => prevCount - 1)}>
        Decrement
      </button>
    </div>
  )
}

how to use a state with an object

  • by default if you are creating an object using useState, it will not merge the different values, this has to be done by the user themselves.

  • in order to do this we can use the spread operator { ...name, lastName: e.target.value } what this is saying is that copy all the properties from the initial and update the lastname. we can do the same for initial name as well.

function UsingStateOne() {
  const [name, setName] = useState({ firstName: "", lastName: "" })
  return (
    <div>
      <form action="">
        <label htmlFor="">FirstName: </label>
        <input
          type="text"
          value={name.firstName}
          onChange={(e) => setName({ ...name, firstName: e.target.value })}
        />
        <label htmlFor=""> Last Name: </label>
        <input
          type="text"
          value={name.lastName}
          onChange={(e) => setName({ ...name, lastName: e.target.value })}
        />
      </form>

      <h2>Your First Name is - {name.firstName}</h2>
      <h2>Your Last Name is - {name.lastName}</h2>
    </div>
  )
}

how to use state with an array

  • same is with array, in order to save all of the number that will be generated on button click we are going to use the spread operator.

  • in the code below we are simply creating a random number and id based on the array length and appending it to the “items”.

function UsingStateOne() {
  const [items, setItems] = useState([])

  const addItem = () => {
    setItems([
      ...items,
      {
        id: items.length,
        value: Math.floor(Math.random() * 10) + 1,
      },
    ])
  }

  return (
    <div>
      <button onClick={addItem}>add a number</button>
      <ul>
        {items.map((item) => (
          <li key={item.id}>
            {item.value} and {item.id}
          </li>
        ))}
      </ul>
    </div>
  )
}

Did you find this article valuable?

Support Ansub Khan by becoming a sponsor. Any amount is appreciated!