useState

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 2 min

useState

useState is a React Hook that lets you add state variables to your components. It is the most commonly used Hook in React.

Basic Syntax

To use useState, you import it from React and call it at the top level of your component.

import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  // ...

useState returns an array with exactly two values:

  1. The current state variable (e.g., count). During the first render, it will match the initial state you passed (0).
  2. A setter function (e.g., setCount) that lets you update the state to a different value and trigger a re-render.

Note: The [count, setCount] syntax is called array destructuring. It’s a JavaScript feature that lets you unpack values from arrays.

Setting State Triggers Renders

When you call the state setter function, you are telling React: “Hey, the state has changed. You need to re-render this component and its children.”

function Toggle() {
  const [isOn, setIsOn] = useState(false);

  return (
    <button onClick={() => setIsOn(!isOn)}>
      {isOn ? 'ON' : 'OFF'}
    </button>
  );
}

Every time the button is clicked, setIsOn is called with a new boolean value. React queues a re-render, calls the Toggle function again, and this time isOn holds the new value.

Rules of Hooks

Because useState is a Hook, it must follow the Rules of Hooks:

  1. Only call Hooks at the top level of your component. Do not call Hooks inside loops, conditions, or nested functions.
  2. Only call Hooks from React Functions (components or custom hooks).

Interview Questions

Q: How do you initialize state lazily, and why would you do it?
A: You initialize state lazily by passing a function instead of a value: useState(() => computeExpensiveValue()). If you pass the value directly (useState(computeExpensiveValue())), the expensive function runs on every single re-render, even though React ignores the result after the first render. Lazy initialization guarantees the function only executes once during the initial mount.