Labs ICT
โญ Pro Login

useState Hook

Adding state to function components.

useState Hook

The useState Hook is your gateway to making components interactive. It lets you add state to function components - that's data that changes over time and triggers re-renders when updated. Before Hooks, you had to write a whole class component just to store a simple counter. Now it's just one line of code. How cool is that?

When you call useState, it returns an array with two things: the current state value and a function to update it. You can name these anything you want, but the convention is [something, setSomething]. React doesn't care about the names - it just knows to pass the current value and the updater function in that order.

Setting Initial State

You can pass an initial value to useState when you call it. This could be a number, string, object, array, or even null. The initial value is only used on the first render - after that, React remembers the current state. It's like setting a default value for a variable, except this variable persists across renders.

function UserProfile() {
  const [name, setName] = useState("Guest")
  const [age, setAge] = useState(25)
  const [hobbies, setHobbies] = useState([])
  return <h1>Hello {name}, age {age}</h1>
}
Try it Yourself โ†’

Updating State Correctly

Here's a common gotcha: never modify state directly. Always use the setter function React gives you. If you have an object, don't do setState({...state, key: value}) - actually, wait, that's exactly what you should do! The key is to always create a new object or use the functional update form when the new state depends on the previous state.

function Counter() {
  const [count, setCount] = useState(0)
  const increment = () => setCount(prev => prev + 1)
  const decrement = () => setCount(prev => prev - 1)
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>+</button>
      <button onClick={decrement}>-</button>
    </div>
  )
}
Try it Yourself โ†’

Multiple State Variables

You can call useState multiple times in the same component to manage different pieces of state. Each call is completely independent - updating one doesn't affect the others. It's like having separate drawers in a filing cabinet. Each one holds its own stuff and can be opened independently.

Some developers prefer to group related state into a single object. Both approaches work, but separate useState calls are often clearer and make it easier to update individual pieces without worrying about spreading other state properties. Choose whatever feels most readable for your use case.

๐Ÿงช Quick Quiz

What hook is used to add state to function components?